Dynamic thumbnail images from ASP.NET

I have had this sampe code of dynamic thumbnail generation kicking around for some time, so I've finally gotten the time to post it here. This sample code is an IHttpHandler implementation that reads a JPG from the filesystem and dynamically generates a thumbnail sized version of the image and emits that to the response stream. What I like about this approach is that you don't need to create a file on the filesystem for the thumbnail as it's all done in memory. This really shows how cool (and useful, of course) IHttpHandler is. Here's the gist of the implementation:

public class ImageHandler : IHttpHandler
{
    // the max size of the Thumbnail
    const int MaxDim = 120;

    public void ProcessRequest(HttpContext ctx)
    {
        // let's cache this for 1 day
        ctx.Response.ContentType = "image/jpeg";
        ctx.Response.Cache.SetCacheability(HttpCacheability.Public);
        ctx.Response.Cache.SetExpires(DateTime.Now.AddDays(1));

        // find the directory where we're storing the images
        string imageDir = ConfigurationSettings.AppSettings["imageDir"];
        imageDir = Path.Combine(
            ctx.Request.PhysicalApplicationPath, imageDir);

        // find the image that was requested
        string file = ctx.Request.QueryString["File"];
        file = Path.Combine(imageDir, file);
        // load it up
        using (Image img = new Bitmap(file))
        {
            // do some math to resize the image
            // note: i know very little about image resizing,
            // but this just seemed to work under v1.1. I think
            // under v2.0 the images look incorrect.
            // *note to self* fix this for v2.0
            int h = img.Height;
            int w = img.Width;
            int b = h > w ? h : w;
            double per = (b > MaxDim) ? (MaxDim * 1.0) / b : 1.0;
            h = (int)(h * per);
            w = (int)(w * per);

            // create the thumbnail image
            using (Image img2 =
                      img.GetThumbnailImage(w, h,
                      new Image.GetThumbnailImageAbort(Abort),
                      IntPtr.Zero))
            {
                // emit it to the response strea,
                img2.Save(ctx.Response.OutputStream,
                    System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
    }

    public bool IsReusable
    {
        get { return true; }
    }

    private bool Abort()
    {
        return false;
    }
}

This was originally published on Brock Allen's Blog here

You might also like...

Comments

Brock Allen Brock Allen is an instructor for DevelopMentor where he teaches .NET and ASP.NET. He also manages the ASP.NET curriculum at DevelopMentor by doing research and course development. When not teaching...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Before software should be reusable, it should be usable.” - Ralph Johnson