Click here to Skip to main content
15,867,453 members
Articles / Web Development / ASP.NET

A Simple Image Handler

Rate me:
Please Sign up or sign in to vote.
4.25/5 (8 votes)
14 May 2008CPOL3 min read 69.8K   2.4K   47   14
An ASP.NET Handler for resizing and rotating/flipping images dynamically.

Sample Image

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 the basic functionality can also resize images and rotate/flip an image based on URL query string parameters. Finally, .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, then the image is rendered from the cache as a JPEG, saving both response time and processing power. If this cache does not exist, then the image will 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.

C#
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, when both the height and width are passed, the image will be resized.

C#
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.

C#
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 use 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.

C#
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 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 CodeProject 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 or another 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.

Latest Downloads

License

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


Written By
Software Developer (Senior) Arroweye Solutions
United States United States
I am a .net software developer based out of Chicago.

Comments and Discussions

 
GeneralMy vote of 5 Pin
crazie.coder8-Jul-13 20:50
professionalcrazie.coder8-Jul-13 20:50 
QuestionThanks Pin
batra_priya11-Jun-13 0:03
batra_priya11-Jun-13 0:03 
QuestionImagehandler.ashx file is not working after I migrate my website from IIS6 to IIS7.5 Pin
min yeko29-Nov-12 19:46
min yeko29-Nov-12 19:46 
QuestionHow do I remove Caching Pin
kunal.codes4-May-10 0:29
kunal.codes4-May-10 0:29 
GeneralA border is automatically added when resizing images. Pin
Dix Mars27-Dec-08 6:40
Dix Mars27-Dec-08 6:40 
AnswerRe: A border is automatically added when resizing images. Pin
www-solutions5-May-09 14:05
www-solutions5-May-09 14:05 
GeneralRe: A border is automatically added when resizing images. Pin
jrhea5-May-09 16:38
jrhea5-May-09 16:38 
GeneralRe: A border is automatically added when resizing images. Pin
Dix Mars1-Jun-09 18:24
Dix Mars1-Jun-09 18:24 
Generaldownload not working, can you pls repair the links Pin
jalal_haddad10-Dec-08 0:30
jalal_haddad10-Dec-08 0:30 
GeneralRe: download not working, can you pls repair the links Pin
jrhea10-Dec-08 2:13
jrhea10-Dec-08 2:13 
GeneralShould be working now.. Pin
jrhea8-May-08 7:29
jrhea8-May-08 7:29 
Generalsorry... Pin
jrhea8-May-08 6:18
jrhea8-May-08 6:18 
QuestionDownloads do not work? Pin
glacierdigital6-May-08 9:00
glacierdigital6-May-08 9:00 
AnswerRe: Downloads do not work? Pin
SteveAtICS8-May-08 4:53
SteveAtICS8-May-08 4:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.