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

时间:2012-04-20 14:26:58

标签: c# gdi+ system.drawing

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

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次给几个不同的用户。我无法访问触发问题的实际文件。

任何有关此处可能发生的事情的线索都将受到赞赏。

2 个答案:

答案 0 :(得分:3)

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

Stream.Read Method

答案 1 :(得分:0)

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

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;