This question is related to this: It is not possible to display an image in HttpContext.Response.OutputStream . This is not a duplicate.
When I try to save PNG to Response.OutputStream, I experience inconsistent behavior between the local development environment and the production environment. Namely, the code that I used initially worked fine locally, but it crashed on the production server.
Here is the source code that worked locally:
using (Bitmap bmp = challenge.RenderImage()) {
bmp.Save(context.Response.OutputStream, ImageFormat.Png);
}
Despite working locally when I deployed it to a production server, I received an application error:
A common error occurred in GDI +.
After some digging, I determined that the problem was that “ Saving a PNG image requires a stream to search for. ” - which is Response.OutputStream is not. The problem was easily mitigated by first writing the Bitmap to System.IO.MemoryStream and then to Response. OutputStream.
using (Bitmap bmp = challenge.RenderImage()) {
using(MemoryStream ms = new MemoryStream()) {
bmp.Save(ms, ImageFormat.Png);
ms.WriteTo(context.Response.OutputStream);
}
}
I am curious to know why the source code worked fine locally, but failed on the production server? The justification for the code error seems pretty black and white to me, so I don’t understand why there may be a mismatch specific to the environment.
source
share