无法从SQL Server检索图像

时间:2014-07-02 07:30:58

标签: c# sql .net sql-server-2008

我将图像从网络摄像头存储到sql server但无法将图像检索回图片框。这是将图像从图片框存储到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(); 

从数据库到图片框检索图像的代码: -

               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;

1 个答案:

答案 0 :(得分: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;

                    }
                }
            }
        }