ASP.Net PNG and the dreaded “a generic error occurred in gdi+”

If you ever make a PNG on the fly using ASP.Net and try to write it directly to the Response.OutputStream you’ll get the exception “a generic error occurred in gdi+“. If you change the output type to JPG or GIF it runs just fine, just PNG breaks.

Now usually .Net exceptions are pretty easy to trace (at least for me) just by name but if you try searching for a generic error guess what you get? Generic results. The problem is that the PNG encoder needs a “seekable stream” when outputing the image and the Response.OutputStream is not seekable. Luckily the fix is easy, just write it to a MemoryStream (which is seekable) and then BinaryWrite the MemoryStream.

Assume that BI is a System.Drawing.Image. Instead of:

BI.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png)

you need to use:

Using MS As New MemoryStream()
    BI.Save(MS, System.Drawing.Imaging.ImageFormat.Png)
    Response.BinaryWrite(MS.GetBuffer())
End Using