How to put image in a picture box from a byte[] in C#

谁说我不能喝 提交于 2019-11-28 23:23:21
John Woo

This function converts byte array into Bitmap which can be use to set the Image Property of the picturebox.

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
byte[] imageSource = **byte array**;
Bitmap image;
using (MemoryStream stream = new MemoryStream(imageSource))
{
   image = new Bitmap(stream);
}
pictureBox.Image = image;
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();
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);

The ImageConverter class in the System.Drawing namespace can do the conversion:

byte[] imageArray = **byte array**
ImageConverter converter = new ImageConverter();
pictureButton.Image = (Image)converter.ConvertFrom(imageArray);

If you want to use BinaryReader to convert then use like this,

FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);

BinaryReader br = new BinaryReader(fs);

byte[] img = br.ReadBytes((int)fs.Length);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!