将System.Byte []转换为图像并以winform格式显示在图片框中

时间:2011-03-25 10:29:32

标签: c#

我有一张存储图片的表格,在加载表格时我检索到数据和数据在System.Byte []中。

我希望它以窗口形式显示在图片框中。  我正在使用C#语言和SQL SERVER 2005

我的代码是这样的:

            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"

请有人帮助我......这对我的项目非常重要。提前谢谢

4 个答案:

答案 0 :(得分:3)

将流媒体位置设置回开头

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

问题是流位置在最后,所以当Image尝试读取它时,它将读取零字节

答案 1 :(得分:3)

 MemoryStream ms = new MemoryStream(byteBLOBData);

位置确实是你的问题。但是,构造函数已经初始化了内存流,您不必调用Write()。只需删除它,位置也可以。

答案 2 :(得分:3)

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;
}

答案 3 :(得分:1)

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;