Converting an image to byte array and vice versa

If you want to store images in a database you will need to convert the image into a byte array. Here are a couple of methods to assist in converting an image to and from a byte array.

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

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

This next 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 created is returned in this method.

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

Leave a Reply