5,316,870 members and growing! (16,737 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Samples     Intermediate License: The Code Project Open License (CPOL)

A Simple Image Handler

By jrhea

An ASP.NET Handler for resizing and rotating/flipping images dynamically
C# (C# 1.0, C# 2.0, C# 3.0, C#), VB (VB 7.x, VB 8.0, VB), .NET (.NET, .NET 2.0), GDI+, ASP.NET, Dev, Design

Posted: 5 May 2008
Updated: 14 May 2008
Views: 5,419
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
5 votes for this Article.
Popularity: 2.71 Rating: 3.88 out of 5
0 votes, 0.0%
1
1 vote, 20.0%
2
0 votes, 0.0%
3
2 votes, 40.0%
4
2 votes, 40.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Sample Image - maximum width is 600 pixels

Introduction

This article explains the use of an ASP.NET handler to serve up images. Why use an image handler? The most important reason is to prevent broken image links. I focused on creating an image handler that in addition to that basic functionality can also resize images and rotate/flip an image based on url query string parameters. Finally, the .net data caching is used to speed up the performance of serving images.

Using the Code

The first thing the handler does is to check if the image, stored as a bitmap, exists in the .net data caching engine. There are two levels of caching implemented for this handler. The first cache is based on the query string. So for example the url request "ImageHandler.ashx?image=images/rover.gif&width=200&height=400" would have a cache based on the url parameters "?image=images/rover.gif&width=200&height=400". If this cache is found in than the image is rendered from the cache as a jpeg saving both response time and processing power. If this cache does not exist than the image will attempted to be retrieved and processed. This is where the second caching layer exists. Since the original bitmap can be requested in several ways based on the url parameters the original image is also cached after it is retrieved resulting in fewer requests to the hard drive.

        if (context.Cache[("ImageQueryURL-" + context.Request.QueryString.ToString())] != null)
        {
            bitOutput = (Bitmap)context.Cache[("ImageQueryURL-" + context.Request.QueryString.ToString())];
        }

In this step we are determining the dimensions to resize the image to. The height and/or the width can be passed as a query string parameter to determine the output size. In this code block both when both the height and width are passed the image will be resized.

    double inputRatio = Convert.ToDouble(bitInput.Width) / Convert.ToDouble(bitInput.Height);
    
    if (!(String.IsNullOrEmpty(context.Request["width"])) && !(String.IsNullOrEmpty(context.Request["height"])))
    {
        _width = Int32.Parse(context.Request["width"]);
        _height = Int32.Parse(context.Request["height"]);
        return true;
    }
    

After we have obtained the image the query string is again checked, this time for rotating and flipping.

    if (String.IsNullOrEmpty(context.Request["RotateFlip"]))
    {
        return bitInput;
    }
    else if (context.Request["RotateFlip"] == "Rotate180flipnone")
    {
        bitOut.RotateFlip(RotateFlipType.Rotate180FlipNone);
    }
    

Finally, we resize the image using the Windows GDI+ engine. We used high quality rendering modes to reduce artifacting, but this comes at the price of processing and response time. This is another reason that the data caching is an important part of this class.

        Bitmap resizedBitmap = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);

        Graphics g = Graphics.FromImage(resizedBitmap);
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        Rectangle rectangle = new Rectangle(0, 0, newWidth, newHeight);
        g.DrawImage(inputBitmap, rectangle, 0, 0, inputBitmap.Width, inputBitmap.Height, GraphicsUnit.Pixel);
        g.Dispose();
        

Ways to Improve/Build upon this code

The objective of this project was to make a simple and easy to use image handler, where all the code is contained in the one class. I made sure to put all code in the single handler class so that it could easily be dropped into a project, without a lot of configuration hassles. However, there were some compromises that had to be made. Generally, a handler is designed to work against certain file types defined in IIS. I didn't make the code work this way because it wouldn't have been as easy to share with the Code Project community, but it certainly could with a few small modifications. I would also define the noImageUrl as a configuration variable, perhaps in the web.config file other configuration file.

Lastly, a great advantage of using an image handler is that you disassociate the actual physical location of the images from where they appear to a browser. You may find yourself in the situation where the physical location of your images needs to be moved, which has cascading impacts on many different components of your system that may have hard coded image paths.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

jrhea


I am a .net software developer based out of Chicago.
Occupation: Software Developer
Company: eNeighborhoods.com
Location: United States United States

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralShould be working now..memberjrhea8:29 8 May '08  
Generalsorry...memberjrhea7:18 8 May '08  
GeneralDownloads do not work?memberLordGentle10:00 6 May '08  
GeneralRe: Downloads do not work?memberLabcoat3255:53 8 May '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 14 May 2008
Editor:
Copyright 2008 by jrhea
Everything else Copyright © CodeProject, 1999-2008
Web09 | Advertise on the Code Project