C# - 输出图像到响应输出流时出现GDI+错误

41

向输出流输出图像时,是否需要临时存储?当将图像保存到文件时,我会收到通常与文件夹权限错误相关的“通用GDI+”错误。

我对这个图像唯一的操作是添加一些文本。即使在不进行修改的情况下直接输出图像,我仍然会收到错误。例如,执行以下操作将导致出现错误:

using (Bitmap image = new Bitmap(context.Server.MapPath("images/stars_5.png")))
{
    image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
}

在我的本地机器上运行Windows 7,IIS 7.5和ASP.NET 2.0都很正常,但问题出现在运行Windows Server 2003,IIS 6和ASP.NET 2.0的QA服务器上。

导致错误的代码行是:

image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);

这是堆栈跟踪:

[ExternalException (0x80004005): A generic error occurred in GDI+.]
   System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) +378002
   System.Drawing.Image.Save(Stream stream, ImageFormat format) +36
   GetRating.ProcessRequest(HttpContext context) in d:\inetpub\wwwroot\SymInfoQA\Apps\tools\Rating\GetRating.ashx:54
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

你有没有使用任何源代码控制工具? - cwharris
2个回答

90

需要将PNG(以及其他格式)保存到可寻址的流中。使用中间的MemoryStream可以解决问题:

using (Bitmap image = new Bitmap(context.Server.MapPath("images/stars_5.png")))
{
   using(MemoryStream ms = new MemoryStream())
   {
      image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
      ms.WriteTo(context.Response.OutputStream);
   }
}

这是我看到的第一个使用ms.writeto的答案,所有其他类似的解决方案都尝试了httpResponseMessage response.Content = new StreamContent(ms.toarray()),但对我来说没有用。干得好! - JD E
@Ammar 它是 ASP.NET 中的 System.Web.HttpContext 实例。 - Mark Cidade

10

我只是想补充一点:

Response.ContentType = "image/png";

因此,在不包含 img 标签时,它可以直接在浏览器中查看。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接