简体   繁体   English

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

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

I want this to display in the picture box in window form. 我希望它以窗口形式显示在图片框中。 I am using C# language and SQL SERVER 2005 我正在使用C#语言和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 . 问题在于流位置在末尾,因此当Image尝试读取它时, 它将读取零字节

 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(). 但是,构造函数已经初始化了内存流,您不必调用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;

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

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