C#: Image and Byte Array Conversion

Posted: December 16, 2012 in .Net/C#
Tags: , , ,

The conversion between Image to Byte Array is very useful when processing image. Below are the two simple functions.

public static Image byteArrayToImage(byte[] data)
{
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
     {
          return Image.FromStream(ms);
     }
}

public static byte[] imageToByteArray(Image image)
{
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
          image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
          return ms.ToArray();
     }
}

But, you may receive “A generic error occurred in GDI+” in certain scenarios. Most of them are related to the MemoryStream the above two functions are using.

In one scenario, I converted the byte array to an image first and then convert the same image back to a byte array. I received the GDI+ error. The reason is that the MemoryStream must be kept opened during the lifetime of the Bitmap. To avoid this issue, you can copy the image to a new one. The updated byteArrayToImage is as below.

public static Image byteArrayToImage(byte[] data)
{
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
     {
          return new Bitmap(Image.FromStream(ms));
     }
}
Advertisements
Comments
  1. tanawat64 says:

    I encounter with GDI+ error then I use your solution. It’s work!!
    Thank you so much.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s