Search code examples
c#sql-serverimagememorystream

Load picture from SQL and set it as a picturebox image in C#


I am using this code to load an image from SQL and set it as a picturebox image. but the code does not work. I use "image"/"varbinary(Max)" for Logo image in SQL Server.

byte[] data = (byte[])(DT.Rows[0][18]);
MemoryStream mem = new MemoryStream(data);
pictureBox1.Image = Image.FromStream(mem);

Actually, the last line show error:

Parameter is not valid

this is the way I send the picture to SQL ((object)imageData is the data that I send).

Image img = Image.FromFile(opf.FileName);
MemoryStream tmpStream = new MemoryStream();
img.Save(tmpStream, System.Drawing.Imaging.ImageFormat.Png); // change to other format
tmpStream.Seek(0, SeekOrigin.Begin);
byte[] imageData = new byte[img.Size.Height * img.Height];
tmpStream.Read(imageData, 0, img.Size.Height * img.Height);

Solution

  • Thanks to all for responding me, As I wrote, (object)imageData was the data that I sent to SQL Server. I changed it to (Array)imageData and the problem was solved.