【问题标题】:C# - Outputting image to response output stream giving GDI+ errorC# - 将图像输出到响应输出流给出 GDI+ 错误
【发布时间】:2011-08-03 12:13:08
【问题描述】:

将图像输出到输出流时,是否需要临时存储?将图像保存到文件时,我收到通常与文件夹权限错误相关的“通用 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 的本地机器上一切正常。问题出现在使用 IIS 6 和 ASP.NET 2.0 运行 Windows Server 2003 的 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

【问题讨论】:

  • 您是否正在使用任何源代码控制?

标签: c# asp.net gdi+


【解决方案1】:

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()) 这对我不起作用。干得好!
  • @Ammar 它是 ASP.NET 中的 System.Web.HttpContext 实例。
【解决方案2】:

我只想补充:

Response.ContentType = "image/png";

所以当它不在img标签内时,可以直接在浏览器中查看。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 2022-01-20
    相关资源
    最近更新 更多