33

I want to save user image into a database in C#. How do I do that?

r.r
  • 7,023
  • 28
  • 87
  • 129
  • Take a look at : http://stackoverflow.com/questions/744589/how-do-you-store-a-picture-in-an-image-column/744603#744603 – Canavar Aug 23 '10 at 14:51
  • Possible duplicate of [How to save image in database and display it into Views in MVC 4?](http://stackoverflow.com/questions/20825119/how-to-save-image-in-database-and-display-it-into-views-in-mvc-4) – Paul Sweatte Jul 12 '16 at 14:08
  • Try: https://stackoverflow.com/questions/3548401/how-to-save-image-in-database-using-c-sharp – Ali NajafZadeh Aug 08 '21 at 17:14

9 Answers9

26

Try this method. It should work when field when you want to store image is of type byte. First it creates byte[] for image. Then it saves it to the DB using IDataParameter of type binary.

using System.Drawing;
using System.Drawing.Imaging;
using System.Data;

    public static void PerisitImage(string path, IDbConnection connection)
    {
        using (var command = connection.CreateCommand ())
        {
            Image img = Image.FromFile (path);
            MemoryStream tmpStream = new MemoryStream();
            img.Save (tmpStream, ImageFormat.Png); // change to other format
            tmpStream.Seek (0, SeekOrigin.Begin);
            byte[] imgBytes = new byte[MAX_IMG_SIZE];
            tmpStream.Read (imgBytes, 0, MAX_IMG_SIZE);

            command.CommandText = "INSERT INTO images(payload) VALUES (:payload)";
            IDataParameter par = command.CreateParameter();
            par.ParameterName = "payload";
            par.DbType = DbType.Binary;
            par.Value = imgBytes;
            command.Parameters.Add(par);
            command.ExecuteNonQuery ();
        }
    }
Max Voisard
  • 1,685
  • 1
  • 8
  • 18
jethro
  • 18,177
  • 7
  • 46
  • 42
  • 4
    For those reading this later, `DbType.Binary` handles `varbinary(MAX)` even though the help tooltip says it's limited to 8000 bytes. – Jon Seigel Dec 16 '10 at 15:06
7

You'll want to convert the image to a byte[] in C#, and then you'll have the database column as varbinary(MAX)

After that, it's just like saving any other data type.

Mike M.
  • 12,343
  • 1
  • 24
  • 28
7

This is a method that uses a FileUpload control in asp.net:

byte[] buffer = new byte[fu.FileContent.Length];
Stream s = fu.FileContent;
s.Read(buffer, 0, buffer.Length);
//Then save 'buffer' to the varbinary column in your db where you want to store the image.
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
4

You'll need to serialize the image to a binary format that can be stored in a SQL BLOB column. Assuming you're using SQL Server, here is a good article on the subject:

http://www.eggheadcafe.com/articles/20020929.asp

Dave Swersky
  • 34,502
  • 9
  • 78
  • 118
  • I would not follow this example anymore, there are known vulnerabilities that are related to the BianaryFormatter used. https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide – Mike Jul 20 '21 at 20:54
  • https://stackoverflow.com/questions/3548401/how-to-save-image-in-database-using-c-sharp – Ali NajafZadeh Aug 08 '21 at 17:15
2

My personal preference is not to save the images to a database as such. Save the image somewhere in the file system and save a reference in the database.

Jaydee
  • 4,138
  • 1
  • 19
  • 20
  • 4
    Only useful in a few cases, as you have to make the file system in question open to all the .NET code. It's also inconsistent. Can be useful enough in web apps, as long as you never need to expand onto a webfarm, at which point sharing the files can be a nuisance. – Jon Hanna Aug 23 '10 at 15:01
  • 1
    you can use the SQL http://msdn.microsoft.com/en-us/library/cc949109.aspx - also available in nHIbernate from 2.1 http://zvolkov.com/blog/post/2009/07/20/Whats-new-in-NHibernate-21.aspx serilaizing in the DB is not a good design strategy - having to set permissions on a folder is not a good reason to not do it properly :) –  Aug 25 '10 at 16:32
  • 1
    @cvista I save images to the DB frequently. Drop a memcached instance in the mix and it becomes even more attractive. – Ryan Aug 25 '10 at 19:29
  • 3
    Useful in every case, especially farms. You create a service to save the image and store the reference in SQL Server. The image service automatically populates the farms. YOu get automatic scaleout and redundancy. – RickAndMSFT Mar 18 '12 at 16:35
1

you can save the path of the image in the database or save the image itself as a BLOB ( binary - array of bytes)..it depends on the case you got,if your application is a web application,then saving the path of the image is much better.but if you got a client based application that connects to a centralized database,then you must save it as binary.

Khaled
  • 841
  • 3
  • 13
  • 22
1

Since you are using SQL, would recommend against using adhoc ('writing statements in strings'), especially given that you are loading an image.

ADO.NET can do all of the hard work of mapping, escaping etc for you.

Either create a Stored Procedure, or use SqlParameter to do the binding.

As the other posters say, use VARBINARY(MAX) as your storage type - IMAGE is being depracated.

StuartLC
  • 104,537
  • 17
  • 209
  • 285
-1

I think this valid question is already answered here. I have tried it as well. My issue was simply using picture edit (from DevExpress). and this is how I got around it:

  • Change the PictureEdit's "PictureStoreMode" property to ByteArray: it is currently set to "default" enter image description here
  • convert the control's edit value to bye: byte[] newImg = (byte[])pictureEdit1.EditValue;
  • save the image: this.tbSystemTableAdapter.qry_updateIMGtest(newImg);

Thank you again. Chagbert

Chagbert
  • 722
  • 7
  • 16
  • 1
    the original question is how to save an image into the database using C#, your proposed solution involves adding a third party product from DevExpress rather than implement the solution using C# which is both requested and available. – mknopf May 31 '20 at 16:11
-4
//Arrange the Picture Of Path.***

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);

                    string[] PicPathArray;
                    string ArrangePathOfPic;

                    PicPathArray = openFileDialog1.FileName.Split('\\');

                    ArrangePathOfPic = PicPathArray[0] + "\\\\" + PicPathArray[1];
                    for (int a = 2; a < PicPathArray.Length; a++)
                    {
                        ArrangePathOfPic = ArrangePathOfPic + "\\\\" + PicPathArray[a];
                    }
               }

// Save the path Of Pic in database

                    SqlConnection con = new SqlConnection("Data Source=baqar-pc\\baqar;Initial Catalog=Prac;Integrated Security=True");
                    con.Open();

                    SqlCommand cmd = new SqlCommand("insert into PictureTable (Pic_Path) values (@Pic_Path)", con);
                    cmd.Parameters.Add("@Pic_Path", SqlDbType.VarChar).Value = ArrangePathOfPic;

                    cmd.ExecuteNonQuery();

***// Get the Picture Path in Database.***

SqlConnection con = new SqlConnection("Data Source=baqar-pc\\baqar;Initial Catalog=Prac;Integrated Security=True");
                con.Open();

                SqlCommand cmd = new SqlCommand("Select * from Pic_Path where ID = @ID", con);

                SqlDataAdapter adp = new SqlDataAdapter();
                cmd.Parameters.Add("@ID",SqlDbType.VarChar).Value = "1";
                adp.SelectCommand = cmd;

                DataTable DT = new DataTable();

                adp.Fill(DT);

                DataRow DR = DT.Rows[0];
                pictureBox1.Image = Image.FromFile(DR["Pic_Path"].ToString());
Udo Held
  • 12,314
  • 11
  • 67
  • 93
Syed Baqar Hassan
  • 2,643
  • 2
  • 13
  • 4