繁体   English   中英

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

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

我有一张表格,其中存储了图片,并在加载表格时检索该数据,并且数据在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"

请任何人能帮助我...这对我的项目非常重要。 先感谢您

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

将流位置重新设置为开头

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

问题在于流位置在末尾,因此当Image尝试读取它时, 它将读取零字节

 MemoryStream ms = new MemoryStream(byteBLOBData);

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

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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