![](/img/trans.png)
[英]Image.Save() throws exception "Value cannot be null./r/nParameter name: encoder"
[英]Image.Save crashing: {“Value cannot be null.\r\nParameter name: encoder”}
我试图将图像保存到MemoryStream
但在某些条件下失败。
这是代码:
以下代码成功:
Image img = Bitmap.FromStream(fileStream);
MemoryStream ms = new MemoryStream();
img.Save(ms, img.RawFormat); // This succeeds.
以下代码失败:
Image img = Bitmap.FromStream(fileStream);
Image thumb = img.GetThumbnailImage(thumbWidth, thumbHeight, null, System.IntPtr.Zero);
MemoryStream ms = new MemoryStream();
thumb.Save(ms, thumb.RawFormat); // This fails.
请注意,第二个代码段使用的是使用Image.GetThumbnailImage
创建的图像。
有什么不同? 有谁知道它为什么失败?
我相信这个问题与GetThumbnailImage
文档的这一部分有关:
如果图像包含嵌入的缩略图图像,则此方法将检索嵌入的缩略图并将其缩放到请求的大小。 如果图像不包含嵌入的缩略图图像,则此方法通过缩放主图像来创建缩略图图像。
这可能是间歇性行为(AKA“某些条件”)的原因。 解释在以下Microsoft Connect票证中 :
底层API无法为MemoryBmp图像类型定位编码器。 我们需要对GDI +团队进行调查。 在此期间,您应该能够简单地将ImageFormat更改为ImageFormat.Bmp而不是ImageFormat.MemoryBmp,它应该可以工作。 它仍将使用BMP格式保存到MemoryStream。
很有可能,如果没有嵌入的缩略图, GetThumbnailImage
API生成的新缩略图实际上将具有RawFormat
的MemoryBmp
,它没有关联的编码器 - 因此您看到的是特定的错误消息。
只是不要使用thumb.RawFormat
; 既然你知道它是位图,那么请使用ImageFormat.Bmp
。
PS请注意,虽然我删除了我之前的答案,因为事实证明它与此特定问题无关,但正如文档所指定的那样,正确使用GetThumbnailImage
API仍然很重要; 您必须为callback
参数传递一个有效的委托而不是null
,否则它可能会失败,您仍然需要在using
子句中包装一次性用法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.