Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

asp.net - C# - Outputting image to response output stream giving GDI+ error

When outputting an image to the output stream, does it require temporary storage? I get the "generic GDI+" error that is usually associated with folder permission error when saving an image to file.

The only thing I'm doing to the image is adding some text. I still get the error even when I output the image straight without modifications. For example, doing this will give me the error:

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

Everything works fine on my local machine running Windows 7 with IIS 7.5 and ASP.NET 2.0. The problem is occurring on the QA server which is running Windows Server 2003 with IIS 6 and ASP.NET 2.0.

The line that's giving the error is:

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

Here's the stack trace:

[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:inetpubwwwrootSymInfoQAAppsoolsRatingGetRating.ashx:54
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

PNGs (and other formats) need to be saved to a seekable stream. Using an intermediate MemoryStream will do the trick:

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);
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...