Contact   •   Products   •   Search

Rick Strahl's Web Log

Wind, waves, code and everything in between...
ASP.NET • C# • HTML5 • JavaScript • AngularJs

Streaming a PNG file into Response.OutputStream?


Hmmm… I’m working on an HTTP handler that is returning an image as its end result. The image generation works fine and a generic routine returns a Bitmap image as a result. Finally I write out the image like this:

 

Bitmap bmp = wwWebUtils.CornerImage(backcolor, color, c, Radius, Height, Width);

 

// *** Works:

//bmp.Save(@"c:\projects2005\wwStore\corner.png", ImageFormat.Png);

       

// *** Doesn’t work

Response.ContentType = "image/png";

bmp.Save(Response.OutputStream,ImageFormat.Png);

 

This fails with a generic exception on the page:

 

System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.

 

If I save the image as a Jpg file (ImageFormat.Jpeg) all works fine. It appears there’s some problem with the PNG image streaming.

 

Anybody seen this before? Why would there be a problem streaming a PNG file? The output seems OK – I can write the PNG file to disk no problem, so it looks like the data in the image file is fine.

 

I suppose I can grab the image as bytes and write out the raw binary string, but it seems odd that this shouldn’t work.

Make Donation


Feedback for this Post

 
# re: Streaming a PNG file into Response.OutputStream?
by Anders June 14, 2006 @ 3:10am
I think that you need a seekable stream to save PNG's.

Try to save the PNG to a MemoryStream and write that to the OutputStream witout closing the MemoryStream
# re: Streaming a PNG file into Response.OutputStream?
by Russ Garner June 14, 2006 @ 3:43am
Png's are a special case. Their encoder requires a bi-directional stream. The solution is to stream to a memory stream first and write the contents of that memory stream to OutputStream afterwards.

When you get to caching (which I've just implemented) you'll be writing to a memory stream anyway just to cache the output, so this isn't a big deal.

As far as the GIF end of things goes, the default palletization of the built in GIF encoder leaves something to be desired. I've built in support for an Octree quantizer to deal with this.

Seriously - it's a lot of work. It's probably easier if I just send you some code ;)
# re: Streaming a PNG file into Response.OutputStream?
by DuncanS June 14, 2006 @ 4:02am
Rick, watch out for trying to color match PNG colors to the colors used in your stylesheet - they don't match exactly when renedered. See The Sad Story of PNG Gamma “Correction” http://hsivonen.iki.fi/png-gamma/.
# re: Streaming a PNG file into Response.OutputStream?
by DuncanS June 14, 2006 @ 4:03am
# re: Streaming a PNG file into Response.OutputStream?
by Rick Strahl June 14, 2006 @ 4:45am
Yes streaming to a memory-stream works - I added that after I got done here. Thanks for the heads up on the bi-directional nature of PNG. ANd Duncan thanks for the warning about colors - I haven't checked this out...

I really don't want to use PNG but generating a transparent GIF is such a pain in the ass <g>... With IE 7 support for alpha transparency PNG finally in addition to Mozilla, it looked like a viable option.
# Interesting Finds: June 14, 2006 AM edition
by Jason Haley June 14, 2006 @ 8:51am
# re: Streaming a PNG file into Response.OutputStream?
by Nicholas June 14, 2006 @ 10:04pm
Might not have anything to do with what you're doing, but I ran into a problem last week with IIS6 and on-the-fly dynamic compression of ASPX pages. One of my ASPX pages was delivering a PDF file dynamically, and it was being GZIP'd by IIS. This would cause Adobe to freak out most of the time, until you hit refresh and it seemed to correct itself.
# re: Streaming a PNG file into Response.OutputStream?
by Preethi July 19, 2006 @ 2:46am
I also faced with same problem. I got the solution & now its working fine.

MemoryStream MemStream=new MemoryStream();
Bitmap bitmap = new Bitmap(image);
// set the content type
Response.ContentType = "image/png";
//send the image to the memory stream then output
bitmap.Save(MemStream, System.Drawing.Imaging.ImageFormat.Png);
MemStream.WriteTo(Response.OutputStream);

If my soltion work's for you then I'm grateful

Thanks
Best of luck
# re: Streaming a PNG file into Response.OutputStream?
by Aaron July 27, 2006 @ 11:15pm
I too have an issue with the bitmap.Save(...) method and asp.net. I have a project I'm working on where I need to output a barcode on a form. The short of it is when outputing the form in a pdf format the barcode font will not render correctly or not at all (depending on the webserver os) I ended up needing to use the barcode font and some gdi fun to convert a string to an image (base64string) then load that into a dataset that feeds a crystal report file that is ultimately pushed out as a pdf or word doc to the client end. All works good and fine in my little dev world, when I move to stage in test environment - poof GDI+ general exception. All files and file access are the same, the only difference is the webserver os.
# re: Streaming a PNG file into Response.OutputStream?
by maggio September 20, 2006 @ 3:29am
Thanks!
had the same problem and tried hours w/o getting anywhere! Now all's fine! m
# re: Streaming a PNG file into Response.OutputStream?
by Ian October 12, 2006 @ 3:47pm
Many thanks! Had the same problem with PNG not working as an output stream! NOw it works perfectly! Thanks again!
# Common Problems with rendering Bitmaps into ASP.NET OutputStream - Rick Strahl's Web Log
by Rick Strahl's Web Log October 19, 2006 @ 7:25pm
Rendering image output in ASP.NET is not always straight forward as there are situations where images cannot be directly rendered into the Response.OutputStream
# re: Streaming a PNG file into Response.OutputStream?
by James Barnett October 23, 2006 @ 10:20pm
Thank you! I've been having this problem forever and haven't ever been able to find a solution. =]

G'day.
-James
# DotNetSlackers: Streaming a PNG file into Response.OutputStream?
by DotNetSlackers Latest ASP.NET News December 19, 2006 @ 12:12pm
# re: Streaming a PNG file into Response.OutputStream?
by Piotr March 22, 2007 @ 4:22am
Thanks for that fix. It works for me!
# re: Streaming a PNG file into Response.OutputStream?
by Nicolas Fernandez April 09, 2007 @ 8:32pm
Thank you.
Do you really give me very much help with this topic !!!!!
# Outputting to MemoryStream does not solve the problem
by Mark Lyon June 06, 2007 @ 10:33am
The following code does not work. The browser (IE7) generates a javascript error. Jpeg, Bmp, and Gif all work perfectly.

Here is the VB source:
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim Bmp As New Bitmap("C:\Test.Png")
        Dim MS As New MemoryStream
        Bmp.Save(MS, ImageFormat.Png)
        Response.ContentType = "image/png"
        MS.WriteTo(Response.OutputStream)
        MS.Dispose()
        Bmp.Dispose()
    End Sub


Here is the resulting HTML:
&lt;html&gt;&lt;head&gt;&lt;script src=&quot;res://mshtml.dll/objectembed.js&quot;&gt;&lt;/script&gt; &lt;script language=&quot;javascript&quot;&gt;var objectSource=&quot;http://localhost:1467/WebApplication1/GetImage.aspx&quot;; &lt;/script&gt; &lt;/head&gt;&lt;body onload=&quot;ObjectLoad();&quot; leftmargin=0 topmargin=0 scroll=no&gt; &lt;form id=&quot;objectDestination&quot;&gt;&lt;/form&gt; &lt;/body&gt;&lt;/html&gt;
# re: Streaming a PNG file into Response.OutputStream?
by JB November 07, 2007 @ 3:57am
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Bitmap bm = graph.RenderGraph(150, 150, "?", values);

using (ms)
{
using (bm)
{

bm.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.WriteTo(context.Response.OutputStream);

}
}
# re: Streaming a PNG file into Response.OutputStream?
by Roel Mooi January 10, 2008 @ 2:09am
Thank you for this blog. Saved me a lot of time figuring out why my png's where no displaying and the jpg and gif worked fine!!!
# re: Streaming a PNG file into Response.OutputStream?
by Shabdar April 01, 2008 @ 1:07pm
Re:
===============================
The following code does not work. The browser (IE7) generates a javascript error. Jpeg, Bmp, and Gif all work perfectly.

Here is the VB source:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim Bmp As New Bitmap("C:\Test.Png")
Dim MS As New MemoryStream
Bmp.Save(MS, ImageFormat.Png)
Response.ContentType = "image/png"
MS.WriteTo(Response.OutputStream)
MS.Dispose()
Bmp.Dispose()
End Sub
==============================================

This happens if you are debugging website from Visual Studio. If you run it without debugging website it will work fine with IE7 as well.
# re: Streaming a PNG file into Response.OutputStream?
by boatinriver April 07, 2008 @ 1:07am
thank you, i have a same problem, now it's fine. but why this problem happend?
# re: Streaming a PNG file into Response.OutputStream?
by Dave May 20, 2008 @ 6:33pm
Had the same headache - now working fine! Thanks
# re: Streaming a PNG file into Response.OutputStream?
by Andy October 02, 2009 @ 2:03pm
Thank you so much. I ran into the same issue, and was searching forever until I found this.
# re: Streaming a PNG file into Response.OutputStream?
by M.rkino November 03, 2009 @ 5:51am
I solved with a REST WCF service. It works fine with trasparency too.

[OperationContract]
[WebGet(UriTemplate = "/GetImage")]
public Stream GetImage()
{
WebOperationContext.Current.OutgoingResponse.ContentType = "image/png";

System.Drawing.Image image = IMAGE.CreateImage();

MemoryStream mem = new MemoryStream();
image.Save(mem, ImageFormat.Png);
mem.Position = 0;
return mem;
}
# re: Streaming a PNG file into Response.OutputStream?
by Jason Carter May 16, 2010 @ 8:22am
Here's some full sample code of a script that outputs a PNG file of a string of text, accepting several parameters such as color, font, size, and background, and supports transparency.

http://www.dlssoftwarestudios.com/blog/?p=63
# re: Streaming a PNG file into Response.OutputStream?
by Honghong October 01, 2010 @ 8:16am
Thanks for your post! I have been trying for hours and finally got the solution from here. I used Steven Sanderson's Captcha from his book and it does not work once I deployed to the real webserver although it worked on local host.
Your Captcha looks simple and effective without the hassel of image generating.
 


West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2014