简体   繁体   中英

Converting System.Byte[] to the image and display in the picturebox in winform

I have a table where the picture has been stored and while loading the form i retrieve that data and data is in System.Byte[].

I want this to display in the picture box in window form. I am using C# language and SQL SERVER 2005

my code goes like this :

            Byte[] byteBLOBData = (Byte[])(dt.Rows[count]["stud_photo"]);
           MemoryStream ms = new MemoryStream(byteBLOBData);
           ms.Write(byteBLOBData, 0, byteBLOBData.Length);

           photo.Image = Image.FromStream(ms); --- here i am having an error "Parameter not valid"

Please can anyone help me ...Its very important for my project. Thank you in advance

you need to remove the header of an image and then get the image data and add the code below to return image after only getting image data.

public Image byteArrayToImage(byte[] byteBLOBData )
{
     MemoryStream ms = new MemoryStream(byteBLOBData );
     Image returnImage = Image.FromStream(ms);
     return returnImage;
}

Set stream position back to the beginning :

ms.Write(byteBLOBData, 0, byteBLOBData.Length);
ms.Position = 0; // THIS !!!!!
photo.Image = Image.FromStream(ms); 

The problem is the stream position is at the end so when Image tries to read it, it will read zero byte .

 MemoryStream ms = new MemoryStream(byteBLOBData);

Position is indeed your problem. However, the constructor already initializes the memory stream, you don't have to call Write(). Just delete it and the Position will be okay as well.

SqlConnection cnn = new SqlConnection(connetionString);
SqlCommand cmd = new SqlCommand(Query, cnn);

MemoryStream stream = new MemoryStream();
cnn.Open();

byte[] image = (byte[])cmd.ExecuteScalar();
stream.Write(image, 0, image.Length);
cnn.Close();

Bitmap bitmap = new Bitmap(stream);
pictureBox1.Image = bitmap;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM