Library code snippets

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

Comments

  1. 06 Apr 2007 at 19:12
    THIS IS THE WRONG WAY TO DO THIS - at least, in most cases.

    If you call the GetThumbnailImage() method, as stated in the documentation, it will return the thumbnail image EMBEDDED IN THE IMAGE resized to the size you requested.

    In many cases, this isn't what you want. For example, let's say I take a photo from my Minolta 7D, it is 2000x3006 pixels, with an 100x150 embedded thumbnail.

    I now request a "thumbnail" image that is 400x600.  It will take the 100x150 image and blow it up to be 400x600.  It will not take the large image and scale it.

    To do that, you need to create another image, and draw the large image on to it and save the new image.

    The only case where this will work is if the image you want is smaller than the one that is embedded, or if there is no embedded image.  If you are using this generically, then you need to consider someone uploading a 2K x 3K image with a 16x16 embedded thumbnail.. Not pretty when you blow it up to 100x150 or whatever.

    If you want to confirm this problem, just blow up an image to the original size using this method.  Depending on the make of the camera you used to get the image, it will either look good or look like crud.

    Chert
    www.traderhut.com
















  2. 06 Mar 2007 at 22:05
    The framework documentation at http://msdn2.microsoft.com/en-us/library/system.drawing.aspx states that "Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions."

    We have verified that its use crashes asp.net worker processes.

  3. 19 Apr 2006 at 17:35
    Hi ...
     
    The code is very useful.
     
    The problem is i am implementing the code in ASp.NET2005 its not generating the Thumbnails.
     
    i set all the attributes still no luck.
     
    Please help me. how to implement this in 2.0 ann wat are the settings i need to do in web.config or any where else.
     
    Thanks
    Sri
  4. 09 Dec 2005 at 14:55

    Wow, unbeatable!


    Check out its numerous benefits and features:


    - Uploads images without writing even one line of code
    - Informs the user of the status of the uploading process
    - Allows either automatic or manual resizing and cutting of the uploaded image
    - Automatically generates unlimited resizing options from the original image
    - Allows previews of the uploaded images
    - Integrates perfectly with the Microsoft Visual Studio .NET environment


    That's what I needed for my photo gallery! Thanks a lot guys.


    Take a look at their beta version ... *I-Load 1.5 Beta *

  5. 02 Nov 2005 at 11:40

    The easiest way to upload and resize an image to the internet is I-Load.
    This component also create  an unlimited number of thumbnails  from the original image with the required size.
    I-Load is a FREE ASP.NET web control with numerous benefits and features.
    You can download I-Load (it's FREE!) and view an online demo here:


    http://www.radactive.com/en/Products/ILoad/Overview.aspx

  6. 01 Jan 1999 at 00:00

    This thread is for discussions of Dynamic thumbnail images from ASP.NET.

Leave a comment

Sign in or Join us (it's free).

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...
AddThis

Related podcasts

Want to stay in touch with what's going on? Follow us on twitter!