Thursday, November 30, 2006

Code needed to dynamically write a .PNG from ASP.NET

For some strange reason you need to use the following code to dynamically output Jpeg's from an ASP.NET page.

Bitmap bitmap = new Bitmap (Path.Combine (dir , "link-notfound.png"));
bitmap.Save (Response.OutputStream, ImageFormat.Jpeg);

But a >PNG requires the following code :-

Bitmap bitmap = new Bitmap (Path.Combine (dir , "link-notfound.png"));
try
{
// This is the code required to send a PNG file. I'm not
// sure why it differs from the much simpler JPEG code
// bitmap.Save (Response.OutputStream, ImageFormat.Jpeg);
MemoryStream tempST = new MemoryStream();
bitmap.Save (tempST, ImageFormat.Png);
Response.ClearContent();
Response.ContentType = "image/png";
Response.BinaryWrite (tempST.ToArray());
Response.End();
}
catch
{
}
bitmap.Dispose();

No comments: