Convert a bitmap into a byte array

Jeremy McGee picture Jeremy McGee · Sep 8, 2011 · Viewed 387.3k times · Source

Using C#, is there a better way to convert a Windows Bitmap to a byte[] than saving to a temporary file and reading the result using a FileStream?

Answer

prestomanifesto picture prestomanifesto · Sep 8, 2011

There are a couple ways.

ImageConverter

public static byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}

This one is convenient because it doesn't require a lot of code.

Memory Stream

public static byte[] ImageToByte2(Image img)
{
    using (var stream = new MemoryStream())
    {
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        return stream.ToArray();
    }
}

This one is equivalent to what you are doing, except the file is saved to memory instead of to disk. Although more code you have the option of ImageFormat and it can be easily modified between saving to memory or disk.

Source: http://www.vcskicks.com/image-to-byte.php