0

I am storing the image from web cam to sql server but unable to retrieve the image back to picture box. Here is code to store image from picture box to sql server.

            MemoryStream ms1 = new MemoryStream();
            userpic2.Image.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] img_arr1 = new byte[ms1.Length];
            ms1.Read(img_arr1, 0, img_arr1.Length);
            SqlCommand cmd = new SqlCommand("INSERT INTO CustomerDetails(Photo) values  (@pic)", con);
            cmd.Parameters.AddWithValue("@pic", img_arr1);
            cmd.ExecuteNonQuery(); 

Code to retrieve image from database to picturebox:-

               MemoryStream stream = new MemoryStream();

                SqlCommand command = new SqlCommand("select Photo from CustomerDetails where Fname='" + Glist.SelectedItem + "'", con);
                byte[] image = (byte[])command.ExecuteScalar();
                stream.Write(image, 0, image.Length);

                Bitmap bitmap = new Bitmap(stream);/// here i am getting error as INVALID PARAMETER
                userpic2.Image = bitmap;
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • I think this post may help: http://stackoverflow.com/questions/6333681/c-sharp-parameter-is-not-valid-creating-new-bitmap – Prisoner Jul 02 '14 at 07:36
  • What's the exact error message? Please post the message and stack trace. Also, could be an issue with the image size, so you might want to check for that. http://msdn.microsoft.com/en-us/library/z7ha67kw.aspx – shree.pat18 Jul 02 '14 at 07:39

1 Answers1

0
            byte[] bt;
            using (SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=true"))
            {
            conn.Open();

            using (SqlCommand cmd = new SqlCommand("SELECT Photo FROM Employees WHERE EmployeeID=2", conn))
            {
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        bt = reader["Photo"] as byte[] ?? null;
                        ImageConverter ic = new ImageConverter();
                       System.Drawing.Bitmap img = (System.Drawing.Bitmap)ic.ConvertFrom(bt);
                        pictureBox1.Image = img;

                    }
                }
            }
        }
Prasad
  • 1
  • 1