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?
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(); } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With