简体   繁体   中英

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

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#?

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 Bitmap Load Picturebox Image From Memory?

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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