Search code examples
c#memorybitmaparrays

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?


Solution

  • 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.