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

Kevin picture Kevin · Mar 6, 2012 · Viewed 61.1k times · Source

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?

Answer

John Woo picture John Woo · Mar 6, 2012

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