Jeremy McGee Jeremy McGee - 2 months ago 22
C# Question

Convert a bitmap into a byte array

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

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)
{
    byte[] byteArray = new byte[0];
    using (var stream = new MemoryStream())
    {
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);

        byteArray = stream.ToArray();
    }
    return byteArray;
}

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