Thursday, July 03, 2008

Tip: Convert image to byte array and vice versa

Very often, when you are developing a Windows Mobile application you need to convert an image displayed in a PictureBox control to a byte array. You can do so using:

public byte[] ImageToByteArray(Image img)
{
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}


You can call this function like this:

byte[] data = ImageToByteArray(pictureBox1.Image);

Conversely, if you want to convert a byte array to back to an image so that it can be displayed in a PictureBox control, you can use the following function:

public Image ByteArrayToImage(byte[] data)
{
MemoryStream ms = new MemoryStream(data);
Image img = new Bitmap(ms);
return img;
}

You can use this as follows:

pictureBox2.Image = ByteArrayToImage(data);

2 comments:

sachin's said...

i am having picture with microsoft ink and saved it in binary format
. and i have to show the image but it give error "Parameter Not valid" at

public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream bipimag = new MemoryStream(byteArrayIn);
Image imag = new Bitmap(bipimag); //gives error here
return imag;

}

Matta said...

Hi Sachin,

Correct the Code Line in your method block as follows.

Image imag = Image.FromFile(new Bitmap(bipimag));

and then check it it will work fine