问题描述
我正在制作远程桌面共享应用程序,我在其中捕获桌面图像并将其压缩并将其发送给接收器.要压缩图像,我需要将其转换为字节 [].
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[].
目前我正在使用这个:
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;
}
但我不喜欢它,因为我必须将它保存在 ImageFormat 中,这也可能会耗尽资源(减慢速度)并产生不同的压缩结果.我已经阅读了使用 Marshal.Copy 和 memcpy 但我我无法理解它们.
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?
推荐答案
没有.为了将图像转换为字节数组,您必须指定图像格式 - 就像将文本转换为字节数组时必须指定编码一样.
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.
如果您担心压缩伪影,请选择无损格式.如果您担心 CPU 资源,请选择一种无需压缩的格式 - 例如,只需原始 ARGB 像素.但这当然会导致更大的字节数组.
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.
这篇关于将图像转换为字节数组的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!