Wrox Home  
Search
ASP.NET 2.0 MVP Hacks and Tips
by David Yack, Joe Mayo, Scott Hanselman, Fredrik Normén, Dan Wahlin, J. Ambrose Little, Jonathan Goodyear
May 2006, Paperback


Compositing Images with an HttpHandler

Recently, I had a back-end black-box system that was sending me two images that were Base64 encoded — that is, binary data encoded as a string, within an XML response. The images were of the front and back of a check. However, the requirement from the client was to show a single composite check image in the user's browser with the front image stacked on top of the back image with a single HTTP GET request. Of course, it has to be secure because this is a check we're talking about, so no writing to temp files!

Here's my solution, implemented as an HttpHandler, so the HTML would include something like the following:

<img src="checkimage.ashx?whatever=4&something=6">

The checkimage.ashx endpoint could be configured in the application's web.config HttpHandlers section, or presented as a small text file like this:

<% @ webhandler language="C#" class="MVPHacks.ExampleCompositingImageHandler" %>

The point is to make sure that ASP.NET knows how to map a request to that request's handler. The simple one-line ashx file exists for one purpose and one purpose only — to be an endpoint, and in existing, to provide a mapping. Most folks prefer to do their mapping within the web.config because everything is centralized and easily changed. Others find this frustrating because their first instinct is to assume that every file that appears in the browser's address bar corresponds to a file on disk. Neither way is better than the other but I prefer the flexibility of the web.config method.

Listing 2 has a few details snipped out that are specific to the request I made to the back-end mainframe system. I've replaced that with the simple request/response model to imply an XML Web Services method. The check images are in the res.ImageFront and res.ImageBack properties as byte arrays.

Listing 2: An image compositing HttpHandler
C#
public class ExampleCompositingImageHandler : IHttpHandler
{
   public SomeCheckImageHandler(){}    

 public void ProcessRequest(HttpContext context)
   {
    context.Response.ContentType = "image/jpeg";
    //some stuff snipped
    GetCheckImageRequest req = new GetCheckImageRequest();
    //some stuff snipped, get the params from the QueryString
    GetCheckImageResponse res = banking.GetCheckImage(req);
    //some stuff snipped
    if (res.ImageBack != null)
    {
        //merge them into one image
        using(MemoryStream m = new MemoryStream(res.BackImageBytes))
        using(Image backImage = System.Drawing.Image.FromStream(m))
        using(MemoryStream m2 = new MemoryStream(res.BrontImageBytes))
        using(Image frontImage = System.Drawing.Image.FromStream(m2))
        using(Bitmap compositeImage = new 
      Bitmap(frontImage.Width,frontImage.Height+backImage.Height))
using(Graphics compositeGraphics = Graphics.FromImage(compositeImage))
        {
     compositeGraphics.CompositingMode = CompositingMode.SourceCopy;
     compositeGraphics.DrawImageUnscaled(frontImage,0,0);
     compositeGraphics.DrawImageUnscaled(backImage,0,frontImage.Height);
     compositeImage.Save(context.Response.OutputStream,
        ImageFormat.Jpeg);
        }
    }
    else //just show the front, we've got no back
    {
        using(MemoryStream m = new MemoryStream(frontImageBytes))
        using(Image image = System.Drawing.Image.FromStream(m))
        {
            image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        }
    }
   }
}
VB
Public Class ExampleCompositingImageHandler
    Inherits IHttpHandler
    
  Public Sub ProcessRequest(ByVal context As HttpContext)
    context.Response.ContentType = "image/jpeg"
    'some stuff snipped
    Dim req As GetCheckImageRequest = New GetCheckImageRequest
    'some stuff snipped, get the params from the QueryString
    Dim res As GetCheckImageResponse = banking.GetCheckImage(req)
    'some stuff snipped
    If (Not (res.ImageBack) Is Nothing) Then
        'merge them into one image
   Using m As MemoryStream = New MemoryStream(res.BackImageBytes)
     Using backImage As Image = System.Drawing.Image.FromStream(m)
       Using m2 As MemoryStream = New MemoryStream(res.BrontImageBytes)
         Using frontImage As Image = System.Drawing.Image.FromStream(m2)
           Using compositeImage As Bitmap = 
New Bitmap(frontImage.Width, (frontImage.Height + backImage.Height))
             Using compositeGraphics As Graphics = 
                 Graphics.FromImage(compositeImage)
compositeGraphics.CompositingMode = CompositingMode.SourceCopy
compositeGraphics.DrawImageUnscaled(frontImage, 0, 0)
compositeGraphics.DrawImageUnscaled(backImage, 0, frontImage.Height)
compositeImage.Save(context.Response.OutputStream, ImageFormat.Jpeg)
             End Using
           End Using
         End Using
       End Using
     End Using
   End Using
      Else
          Dim m As MemoryStream = New MemoryStream(frontImageBytes)
          Dim image As Image = System.Drawing.Image.FromStream(m)
          image.Save(context.Response.OutputStream, ImageFormat.Jpeg)
      End If
  End Sub
End Class

Note a few interesting things about this example. First, the manipulation of streams enables you to save the contents of the stream directly to the response object, as in this line:

image.Save(context.Response.OutputStream, ImageFormat.Jpeg)

Another thing of note is my potentially excessive use of the using statement. Many classes within the .NET Base Class Library are disposable. That is, they are thin wrappers around physical resources that really should be released as soon as you are done with them. Many of the classes within GDI+, the Graphics Device Interface, hold on to unmanaged resources. Rather than wait for the garbage collector to clean up after me, I prefer to be very explicit and dispose of these resources directly. The using statement provides determinism, and while it doesn't release the object reference itself, it does promise to clean up the resources that object manages. After an object is disposed, you mustn't use it. Some may call this stylistic and may disagree, but I feel that is deterministic and a best practice.

The last interesting thing to note is that in the interest of robustness this handler draws the front check image by itself if the back is not returned. This allows more flexibility and renders the hack reusable.

Note that the Using statement was added in VB in .NET 2.0. You'll need to remove it to use this code under VB.NET 1.1. The Using statement in VB is equivalent to a try/finally block in which the finally block calls Dispose() on the variable referenced.

Scott Hanselman is a co-author of ASP.NET 2.0 MVP Hacks and Tips (Wrox, 2006, ISBN 0-7645-9766-3) along with fellow Microsoft MVPs (Microsoft Most Valuable Professionals) David Yack, Joe Mayo, Fredrik Normén, Dan Wahlin, J. Ambrose Little, Jonathan Goodyear. Scott is the chief architect at the Corillian Corporation, an eFinance enabler. He has over 13 years experience developing software in C, C++, VB, COM, and certainly VB.NET and C#. Scott is proud to be both a Microsoft RD (regional director) as well as an MVP for both ASP.NET and Solutions architecture. His Computer Zen blog is one of the most popular developer blogs on the web. Scott is also a co-author of the best-selling ASP.NET 2.0 book Professional ASP.NET 2.0 (Wrox, 2005, ISBN: 0-7645-7610-0) and the upcoming expanded follow-up to that, Professional ASP.NET 2.0 Special Edition (Wrox, 2006, ISBN: 0470041781).