繁体   English   中英

加载图像时“GDI +中发生一般错误”

[英]“A generic error occurred in GDI+” when loading an image

是另一个...堆栈跟踪(有意义的部分):

System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+
   at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData)
   at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement)
   at System.Drawing.Image.FromStream(Stream stream)

尝试打开最终用户上传的图像文件时会发生这种情况。 代码是近似的(剥离到必要部分):

HttpPostedFile file = Request.Files[name];
Stream stream = file.InputStream;
byte[] bytes = new byte[file.ContentLength];
stream.Read(bytes, 0, file.ContentLength);
return bytes;

然后用于

MemoryStream stream = new MemoryStream(bytes);
return Image.FromStream(stream);

所以基本上它试图从内存流加载图像是很困难的。 这不会永远发生。 事实上,我自己无法重现这个问题,但在过去的两周里,它发生了大约20次给几个不同的用户。 我无法访问触发问题的实际文件。

任何可能发生在这里的事情的线索将不胜感激。

stream.Read(bytes, 0, file.ContentLength); 并不意味着它将准确读取file.ContentLength字节。 读取字节可能更少。 您应该检查返回的值。 你可能需要一个循环。

Stream.Read方法

让你的阅读看起来像这样:

HttpPostedFile file = Request.Files[name]; 
Stream stream = file.InputStream; 
byte[] bytes = new byte[ContentLength];
int bytesRead = stream.Read(bytes, 0, ContentLength);
int offset = bytesRead;
while(bytesRead > 0)
{
     bytesRead = stream.Read(bytes, offset, ContentLength - offset);
     offset += bytesRead;
} 
return bytes; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM