Jeremy McGee Jeremy McGee - 1 year ago 135
C# Question

Convert a bitmap into a byte array

Using C#, is there a better way to convert a Windows

to a
than saving to a temporary file and reading the result using a

Answer Source

There are a couple ways.


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.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download