Fastest way to convert Image to Byte array Fastest way to convert Image to Byte array arrays arrays

Fastest way to convert Image to Byte array


There is a RawFormat property of Image parameter which returns the file format of the image.You might try the following:

// extension methodpublic static byte[] imageToByteArray(this System.Drawing.Image image){    using(var ms = new MemoryStream())    {        image.Save(ms, image.RawFormat);        return ms.ToArray();    }}


So is there any other method to achieve this goal?

No. In order to convert an image to a byte array you have to specify an image format - just as you have to specify an encoding when you convert text to a byte array.

If you're worried about compression artefacts, pick a lossless format. If you're worried about CPU resources, pick a format which doesn't bother compressing - just raw ARGB pixels, for example. But of course that will lead to a larger byte array.

Note that if you pick a format which does include compression, there's no point in then compressing the byte array afterwards - it's almost certain to have no beneficial effect.


I'm not sure if you're going to get any huge gains for reasons Jon Skeet pointed out. However, you could try and benchmark the TypeConvert.ConvertTo method and see how it compares to using your current method.

ImageConverter converter = new ImageConverter();byte[] imgArray = (byte[])converter.ConvertTo(imageIn, typeof(byte[]));