Display image from SQL DB on to Picturebox In Windows Forms App
-
Hi, I am trying to display an image from the sql 2000 database on to the picture box control on windows app (VS 2.0). I am able to pull the image in to byte array. I also am able to put the byte array in to the Memory stream by writing it like stream.Write(image, 0, image.Length) However, when i try to create a bitmap out of the memory stream it thorows an exception stating "parameter is not valid". The second approach I tried was to use Image.FromStream(ms1) method, but it also says "parameter is not valid" when it tries to get the image from stream (memory stream). The third approach i tried was writing to a temporary file stream and then read from file using Image.FromFile(strfn, true). This line gets an error stating "Out of memory". Nothing seems to be working. Please shed some light if possible. All i want to do is display an image from sql db field(image field) on to picture box in windows application using C# 2.0 Please look at the code below for detail. The line in bold where I am getting my exceptions. // Put user code to initialize the page here MemoryStream stream = new MemoryStream(); SqlConnection connection = new SqlConnection(@"my connection string"); try { connection.Open(); SqlCommand command = new SqlCommand("select image from images Where EntryDate > '2/15/2007'", connection); byte[] image = (byte[])command.ExecuteScalar(); stream.Write(image, 0, image.Length); Bitmap bitmap = new Bitmap(stream); /////testing 2 MemoryStream ms1 = new MemoryStream(image); exceptionPictureBox.Image = Image.FromStream(ms1); ///testing 3 string strfn = Convert.ToString(DateTime.Now.ToFileTime()); FileStream fs = new FileStream(strfn, FileMode.CreateNew, FileAccess.Write); fs.Write(image, 0, image.Length); fs.Flush(); fs.Close(); exceptionPictureBox.Image = Image.FromFile(strfn, true); /////testing 3 } finally { connection.Close(); stream.Close(); }
Thanks Needy