Answered C#-Image store and read from database

  • Saturday, February 05, 2011 5:51 PM
     
     

    Hi!

    I need to save image from picturebox to database columns (varbinary) and also view image from database to picturebox. I have program connected to database by linq and I displaying the database by datagridview. I use for database sql management 2008.

    Can anyone help me please?

    I am beginner in C#.

    Thank you!

All Replies

  • Saturday, February 05, 2011 6:06 PM
     
     

    Hi Nezmar,

        Kindly, find the below link for adding picture to Sql Server:

        http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/f71da4cd-6f7b-4ddb-b2ed-1fb7a42e0117/

       You can add the Bytes or Binary in the Entity Framework & call SaveChanges() method of DataContext.

      For displaying image,    find the below code:

                try
              {
                FileStream fsRead = new FileStream(ofdPatient.FileName, FileMode.Open);
                BytesOfImage = new Byte[fsRead.Length];
                fsRead.Read(BytesOfImage, 0, BytesOfImage.Length);
                fsRead.Close();
              }
              catch (Exception ex)
              {
                ShowError(ex.Message);
                return;
              }
              pbPatientPhoto.Image = Image.FromFile(ofdPatient.FileName);
              strPatientFileName = ofdPatient.FileName;
            }


    Thanks,

    Paras Sanghani

    http://parassanghani.blogspot.com/

    Mark As Answer if it helped you.

  • Saturday, February 05, 2011 7:44 PM
     
     

    Thank you for fast answer!

    So if I understand, the button for reading image from database can look like this code?


    private byte[] _byteOfImage;

            public Byte[] BytesOfImage
            {
                get { return _byteOfImage; }
                set { _byteOfImage = value; }
            }


            private void button_read(object sender, EventArgs e)
            {
                FileStream fsRead = new FileStream(openDialog.FileName, FileMode.Open);
                BytesOfImage = new Byte[fsRead.Length];
                fsRead.Read(BytesOfImage, 0, BytesOfImage.Length);
                fsRead.Close();


                picturebox1.Image = Image.FromFile(openDialog.FileName);

            }

  • Sunday, February 06, 2011 3:26 PM
     
     

    Hi Nezmar,

       Yes...

        Moreover, the link the above post with help you.

       Please let me know if you need further help!


    Thanks,

    Paras Sanghani

    http://parassanghani.blogspot.com/

    Mark As Answer if it helped you.

  • Sunday, February 06, 2011 7:51 PM
     
     

    Well, maybe I will need help in future.  If it won't bother.

    I very appreciate your help.

    I just want  to create a program that will store images, read images from database and viewing information about images.

    But I don't have experiance with it.

     

    I think that I programmed button for storing  images to database.

     

              private void btn_open_Click(object sender, EventArgs e)
            {

                 if (openDialog1.ShowDialog() != DialogResult.Cancel)
                      {

                      Image image = Image.FromFile(openDialog1.FileName);
                      picturebox1.Image =image;
                      picturebox1.SizeMode = PictureBoxSizeMode.Zoom;
                      }

              }

      public byte[] ImageToByte(Image my_image)
             {
                 MemoryStream Mstream = new MemoryStream();
                 my_image.Save(Mstream, System.Drawing.Imaging.ImageFormat.Jpeg);

                 return Mstream.ToArray();
             }

          private void btn_save_Click(object sender, EventArgs e)
            {

                 byte[] ByteImage=ImageToByte(openDialog.Filename);
                System.Data.Linq.Binary ConvertToBinary = ByteImage;

                datagridview1.Rows[0].Cells[1].Value = ConvertToBinary;

                                      //Cell for varbinary

             }

    This code store me some binary data to database. I'm not sure if its right.

    If I view the store image in datagridview, I see the code of image, but if I view store image in sql management, I se only text <Binary data>.

    How exactly the image look like, if I store it in to the database column (varbinary).

     

    Thank you!

     

     

     

     

     

     

  • Monday, February 07, 2011 3:16 AM
    Moderator
     
     

    Hi Nezmar,

    Welcome to ado.net entity framework and linq to entity forums.

    For you have the image serialize to binary(to store to the database), so if you want to view it from the datagridview you must deserialize it:

    pictureBox.Image = Image.FromStream(stream);// binary stream convert to image

    I hope that would be help you.

    Have a good day.



    If it's helpful for you, Please vote or mark. Thank you!

    David Peng [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

  • Saturday, February 12, 2011 7:10 PM
     
     

    Well I just try to deserialized the image, but it wasn't working.

    I try this code for deserializing.

     public Image ByteToImage(byte[] byte)
             {
                 MemoryStream Mstream = new MemoryStream(byte);
                 Image my_image = Image.FromStream(Mstream);
                 return my_image;


             }

    But I can save the result from datagridview only to object variable.

    How can I convert the object to byte[] which is the parameter of method?

  • Tuesday, February 15, 2011 9:49 AM
    Moderator
     
     Answered

    Hello Nezmar,

    The following code example adds employee information to the Employees table in the Northwind database. A photo of the employee is read from a file and added to the Photo field in the table, which is an image field.

    Codes:

            public static void AddEmployee(string lastName,string firstName,string title,

                DateTime hireDate,int reportsTo,string photoFilePath,string connectionString)

            {

                byte[] photo = GetPhoto(photoFilePath);

     

                using (SqlConnection connection = new SqlConnection(

                  connectionString))

                {

                    SqlCommand command = new SqlCommand(

                      "INSERT INTO Employees (LastName, FirstName, " +

                      "Title, HireDate, ReportsTo, Photo) " +

                      "Values(@LastName, @FirstName, @Title, " +

                      "@HireDate, @ReportsTo, @Photo)", connection);

     

                    command.Parameters.Add("@LastName",

                       SqlDbType.NVarChar, 20).Value = lastName;

                    command.Parameters.Add("@FirstName",

                        SqlDbType.NVarChar, 10).Value = firstName;

                    command.Parameters.Add("@Title",

                        SqlDbType.NVarChar, 30).Value = title;

                    command.Parameters.Add("@HireDate",

                         SqlDbType.DateTime).Value = hireDate;

                    command.Parameters.Add("@ReportsTo",

                        SqlDbType.Int).Value = reportsTo;

     

                    command.Parameters.Add("@Photo",

                        SqlDbType.Image, photo.Length).Value = photo;

     

                    connection.Open();

                    command.ExecuteNonQuery();

                }

            }

            public static byte[] GetPhoto(string filePath)

            {

                FileStream stream = new FileStream(

                    filePath, FileMode.Open, FileAccess.Read);

                BinaryReader reader = new BinaryReader(stream);

     

                byte[] photo = reader.ReadBytes((int)stream.Length);

     

                reader.Close();

                stream.Close();

     

                return photo;

            }

     

    For more information, please see this link:

    http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/5d3fa4d3-ca15-47b2-bf8d-5a0b779a8c12

    I hope this will help you.

     

    Have a nice day,



    Jackie Sun [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

  • Wednesday, August 01, 2012 9:10 AM
     
     

    Hi  I have used the code below to save  images to my database,

    but now I want to know how I can get the picture from the database to a PictureBox

    can you please help me.

     public byte[] ImageToByte(Image my_image)
             {
                 MemoryStream Mstream = new MemoryStream();
                 my_image.Save(Mstream, System.Drawing.Imaging.ImageFormat.Jpeg);

                 return Mstream.ToArray();
             }

          private void btn_save_Click(object sender, EventArgs e)
            {

                 byte[] ByteImage=ImageToByte(openDialog.Filename);
                System.Data.Linq.Binary ConvertToBinary = ByteImage;

                datagridview1.Rows[0].Cells[1].Value = ConvertToBinary;

                                      //Cell for varbinary

             }