Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to convert Image to Byte array

I am making Remote Desktop sharing application in which I capture an image of the Desktop and Compress it and Send it to the receiver. To compress the image I need to convert it to a byte[].

Currently I am using this:

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

But I don't like it because I have to save it in a ImageFormat and that may also use up resources (Slow Down) as well as produce different compression results.I have read on using Marshal.Copy and memcpy but I am unable to understand them.

So is there any other method to achieve this goal?

like image 573
user2529551 Avatar asked Jun 27 '13 19:06

user2529551


2 Answers

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

// extension method public static byte[] imageToByteArray(this System.Drawing.Image image) {     using(var ms = new MemoryStream())     {         image.Save(ms, image.RawFormat);         return ms.ToArray();     } } 
like image 50
Newt Avatar answered Sep 23 '22 08:09

Newt


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.

like image 44
Jon Skeet Avatar answered Sep 25 '22 08:09

Jon Skeet