Monday, January 18, 2010

Saving image from binary stream

In a project I encountered a problem where I needed to capture binary stream of an image which was drawn on flash and was sent to an ASPX page to handle the stream, convert it into the same image that was drawn and save it to disk (on the server) or throw it out of the browser as a download.
Google got exact place for me here, but the food was not yet ready to be fed. It is really annoying to see large number of GDI+ System.Drawing Exceptions. So, here is what I stopped at fighting the those exceptions-
protected void Page_Load(object sender, EventArgs e)
    {
        //Get the stream
        Stream input = (Stream)Request.InputStream;

        Bitmap bmp = new Bitmap(input);

        // Clear current content and set returned content type
        Response.Clear();
        Response.ContentType = "image/jpeg";
        
        // Save to the Response.OutputStream object
        bmp.Save(Response.OutputStream, ImageFormat.Jpeg);

        bmp.Dispose();
        Response.End();
    }

2 comments:

  1. I get, 'Parameter not valid' on line 6. Doesn't seem to work. Any ideas?

    ReplyDelete
  2. I see this could be a memory leak issue.

    If you're on .Net 4.0 framework, try resetting current location in the stream-

    MemoryStream ms = new MemoryStream();
    Request.InputStream.CopyTo(ms);
    ms.Seek(0, SeekOrigin.Begin);
    Bitmap bmp = new Bitmap(ms);

    ReplyDelete