Tuesday, April 30, 2013

Write an image to the reponse of an aspx page.

I recently had the requirement to read image data from a memory stream and write it to the response of an aspx page.  This page was to be used as the source for an image control and should take query string values to get the image data (as part of a containing data contract) by an id and then write the image directly to the response.  Here is the code I ended up with:
public partial class DisplayImageThumbnail : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        String imageId= Request.QueryString["imageId"];
        imageId = imageId?? "-1";
        Bitmap image;       
        try
        {
           // get data contract containing image from service
           CustomImage csImg = ImageInteraction.GetImageById(imageId);
           image = csImg.ImageData;
        }
        catch
        {
           // show a 'no image' image in case of error or n/a
           image = (Bitmap)Bitmap.FromFile(Server.MapPath(String.Format("../Images/no_image.jpg"));
        } 
       
        // will render blank if no image.
        Response.ContentType = "image/jpeg";
        image.Save(Response.OutputStream, ImageFormat.Jpeg);
    }
}

Simple little method once I figured it out, but it seemed like it might help someone else in a similar situation.