Introduction
Image to byte array class:

Recently I was looking for a class which could convert an System.Drawing.Image to byte[] array and vice versa.  After
a lot of search on google I realised that it would be faster for me to write this class and also share
it with the community.


The class which I wrote is called ImageConverter.cs

The class has two methods

First Method : Convert Image to byte[] array

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


This method uses the System.Drawing.Image.Save method to save the image to a memorystream.
The memory stream can then be used to return a byte array using the .ToArray() method in the
MemoryStream class.

Second Method : Convert byte[] array to Image

public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;

}

This method uses the Image.FromStream method in the Image class to create a method from
a  memorystream which has been created using a byte array.  The image thus created is returned
in this method.

The way I happen to use this method was to transport an image to a web service, by converting it
to a byte array and vice-versa.

Hope this class is useful to the community as well.  The code of ImageConverter.cs is attached below.

Rajan Tawate

Introduction
Image to byte array class:

Recently I was looking for a class which could convert an System.Drawing.Image to byte[] array and vice versa.  After
a lot of search on google I realised that it would be faster for me to write this class and also share
it with the community.


The class which I wrote is called ImageConverter.cs

The class has two methods

First Method : Convert Image to byte[] array

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


This method uses the System.Drawing.Image.Save method to save the image to a memorystream.
The memory stream can then be used to return a byte array using the .ToArray() method in the
MemoryStream class.

Second Method : Convert byte[] array to Image

public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;

}

This method uses the Image.FromStream method in the Image class to create a method from
a  memorystream which has been created using a byte array.  The image thus created is returned
in this method.

The way I happen to use this method was to transport an image to a web service, by converting it
to a byte array and vice-versa.

Hope this class is useful to the community as well.  The code of ImageConverter.cs is attached below.

Rajan Tawate