C# - 将图像输出到响应输出流,给出GDI +错误

Dan*_*iel 41 c# asp.net gdi+

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

我正在对图像做的唯一事情是添加一些文本.即使我直接输出图像而没有修改,我仍然会得到错误.例如,这样做会给我错误:

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

在运行带有IIS 7.5和ASP.NET 2.0的Windows 7的本地计算机上,一切正常.问题出现在运行带有IIS 6和ASP.NET 2.0的Windows Server 2003的QA服务器上.

给出错误的行是:

image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
Run Code Online (Sandbox Code Playgroud)

这是堆栈跟踪:

[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
Run Code Online (Sandbox Code Playgroud)

Mar*_*ade 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);
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 甜蜜,有效!谢谢马克!你的丰富知识挽救了我的一天! (4认同)

小智 10

我只想补充一下:

Response.ContentType = "image/png";
Run Code Online (Sandbox Code Playgroud)

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