[英]Convert Byte to Image jpg
i have a problem with convert byte[] to .jpg file. 我将byte []转换为.jpg文件时遇到问题。 When I try to convert byte, I got a exception in this method:
当我尝试转换字节时,此方法出现异常:
using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
{
ms.Write(bytes, 0, bytes.Length);
Image image = Image.FromStream(ms, true, false);
}
Exception: 例外:
The parameter is invalid in System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData)
该参数在System.Drawing.Image.FromStream中无效(流流,布尔值useEmbeddedColorManagement,布尔值validateImageData)
Any suggestion? 有什么建议吗?
Solution * : Remove the line: ms.Write(bytes, 0, bytes.Length);
解决方案* :删除以下行:
ms.Write(bytes, 0, bytes.Length);
* If this doesn't work, the bytes
array doesn't contain valid image data. *如果这不起作用,则
bytes
数组不包含有效的图像数据。
Reason: 原因:
This line initializes a MemoryStream
with the bytes in a byte array. 该行使用字节数组中的字节初始化
MemoryStream
。 It will start the stream at position 0 (the beginning): 它将在位置0(开始)处开始流:
using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
and in your case it can be simplified to: 在您的情况下,可以简化为:
using (MemoryStream ms = new MemoryStream(bytes))
This line then writes the same bytes into the stream. 然后,此行将相同的字节写入流中。 It will leave your stream at position
bytes.Length
(the end): 它将使您的流保留在位置
bytes.Length
(末尾):
ms.Write(bytes, 0, bytes.Length);
This line will try to read an image from the stream starting at the current position (the end). 该行将尝试从当前位置(末尾)开始读取流中的图像。 Since 0 bytes don't make an image, it fails giving you the exception:
由于0个字节不会构成图像,因此它会给您以下异常:
Image image = Image.FromStream(ms, true, false);
As noted by Jimi, it might be better wrapping this up into a method: 如Jimi所述,将其包装成一个方法可能会更好:
public static Image ImageFromByteArray(byte[] bytes)
{
using (MemoryStream ms = new MemoryStream(bytes))
using (Image image = Image.FromStream(ms, true, true))
{
return (Image)image.Clone();
}
}
The reason for using Clone()
is that it can cause trouble saving the image if the original stream has been disposed of. 使用
Clone()
的原因是,如果原始流已被丢弃,则可能导致保存图像时遇到麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.