views:

22

answers:

1

This question is related this one: http://stackoverflow.com/questions/582766/cannot-render-image-to-httpcontext-response-outputstream. It is not a duplicate.

When attempting to save a PNG to the Response.OutputStream I am experiencing inconsistent behavior between the local development environment and the production environment. Namely, the code I was using originally worked fine locally, but failed on the production server.

Here is the original code which worked locally:

using (Bitmap bmp = challenge.RenderImage()) { 
    bmp.Save(context.Response.OutputStream, ImageFormat.Png); 
}

Despite working locally, when I deployed that on the production server I received an Application Error:

A generic error occurred in GDI+.

After some digging I determined that the problem was in the fact that 'Saving a PNG image requires a seekable stream.'- which the Response.OutputStream is not. The problem was easily mitigated by first writing the Bitmap to a System.IO.MemoryStream, and then to the Response.OutputStream.

using (Bitmap bmp = challenge.RenderImage()) {
    using(MemoryStream ms = new MemoryStream()) {
        bmp.Save(ms, ImageFormat.Png);
        ms.WriteTo(context.Response.OutputStream);
    }
}

What I am curious to know is why the original code worked fine locally, but failed on the production server? The reasoning behind the code failing sounds pretty black-and-white to me, so I don't understand why the environment-specific inconsistency could exist at all.

A: 

Theoretically you can implement your own stream that is seekable and add it as filter on your Response.Filter attribute, so maybe Cassini is doing something like that under the hood. This is an example hooking up your own stream: http://www.ericis.com/2007/6/21/Obtaining%20ResponseOutputStreamLength

BurningIce