如何将图像从 C# 中的字节 [] 放入图片框中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9576868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to put image in a picture box from a byte[] in C#
提问by Kevin
I've a byte array which contains an image binary data in bitmap format. How do I display it using the PictureBox control in C#?
我有一个字节数组,其中包含位图格式的图像二进制数据。如何使用 C# 中的 PictureBox 控件显示它?
I went thru a couple of posts listed below but not sure if I need to convert the byte array into something else before sending it to a picturebox. I'd appreciate your help. Thanks!
我浏览了下面列出的几篇文章,但不确定在将字节数组发送到图片框之前是否需要将其转换为其他内容。我很感激你的帮助。谢谢!
How to put image in a picture box from BitmapLoad Picturebox Image From Memory?
采纳答案by John Woo
This function converts byte array into Bitmap which can be use to set the ImageProperty of the picturebox.
此函数将字节数组转换为位图,可用于设置图片Image框的属性。
public static Bitmap ByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
return bm;
}
Sample usage:
示例用法:
pictureBox.Image = ByteToImage(byteArr); // byteArr holds byte array value
回答by Wizetux
byte[] imageSource = **byte array**;
Bitmap image;
using (MemoryStream stream = new MemoryStream(imageSource))
{
image = new Bitmap(stream);
}
pictureBox.Image = image;
回答by DReimer
The ImageConverter class in the System.Drawing namespace can do the conversion:
System.Drawing 命名空间中的 ImageConverter 类可以进行转换:
byte[] imageArray = **byte array**
ImageConverter converter = new ImageConverter();
pictureButton.Image = (Image)converter.ConvertFrom(imageArray);
回答by Md Shahriar
using System.IO;
byte[] img = File.ReadAllBytes(openFileDialog1.FileName);
MemoryStream ms = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(ms);
or you can access like this directly,
或者你可以像这样直接访问,
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
回答by Md Shahriar
You can also convert pictureBox image to byte array like this,
您还可以像这样将图片框图像转换为字节数组,
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] img = ms.ToArray();
回答by Md Shahriar
If you want to use BinaryReader to convert then use like this,
如果您想使用 BinaryReader 进行转换,请像这样使用,
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
BinaryReader br = new BinaryReader(fs);
byte[] img = br.ReadBytes((int)fs.Length);
byte[] img = br.ReadBytes((int)fs.Length);

