SIGN UP MEMBER LOGIN:    
ARTICLE

Generating Good Quality Thumbnail Images in ASP.NET

Posted by Amit Choudhary Articles | ASP.NET Programming November 25, 2009
Thumbnails are small images that are used to preview a large image. One of the applications that uses thumbnails is a photo gallery, The code snippet in this article demonstrates how to generate high quality thumbnails in ASP.NET.
Reader Level:

Some times we need to show the thumbnail of images of big size in our Web pages. One way to do is, just simply use the same image and change the height and width of the image in HTML. Problem with this approach is, image may look blurry or with an uneven ration.

To avoid this problem, you simply create a small image called a thumbnail on the fly using GDI+.

What you have to do is just create a handler in your ASP.NET project and put the following code inside the handler. This code uses Image and Bitmap classes defined in GDI+ to create a small image and sets the quality and encoders of the image.

<%@ WebHandler Language="C#" Class="ThumbnailHandler" %>
using
System;

using System.IO;

using System.Web;

using System.Drawing;

using System.Drawing.Imaging;

using System.Web.Caching;

using System.Configuration;

 

public class ThumbnailHandler : IHttpHandler

{

  //  ----- Variable declaration -------

  int thumbWidth,thumbHeight; String _path;

  bool bRefresh=true;

 

   public void ProcessRequest (HttpContext context)

   {

    String sCacheKey;

    bool bFoundInCache = false;

    // by default

    if(context.Request["Width"]!=null)

        thumbWidth = Int32.Parse(context.Request["Width"]);

    else {

        try { thumbWidth = int.Parse(ConfigurationSettings.AppSettings["DefaultWidth"]); }

        catch (ArgumentNullException ex) { thumbWidth = 50; }

    }

    if(context.Request["Height"]!=null)

        thumbHeight = Int32.Parse(context.Request["Height"]);

    else {

        try { thumbHeight = int.Parse(ConfigurationSettings.AppSettings["DefaultHeight"]); }

        catch (ArgumentNullException ex) { thumbHeight = 40; }

    }

      

  // get path of 'no thumbnail' image

    const String NoThumbFile = "Images/noImageAvailable.jpg";

 

    String sNoThumbPath = context.Request.MapPath(

     context.Request.ApplicationPath.TrimEnd('/') + "/" + NoThumbFile);

 

    // map requested path

       

    if(context.Request["VFilePath"]!=null)

        if (context.Request["VFilePath"].IndexOf(".jpeg") != -1 || context.Request["VFilePath"].IndexOf(".jpg") != -1 || context.Request["VFilePath"].IndexOf(".gif") != -1 || context.Request["VFilePath"].IndexOf(".bmp") != -1 || context.Request["VFilePath"].IndexOf(".png") != -1 || context.Request["VFilePath"].IndexOf(".JPEG") != -1 || context.Request["VFilePath"].IndexOf(".JPG") != -1 || context.Request["VFilePath"].IndexOf(".GIF") != -1 || context.Request["VFilePath"].IndexOf(".BMP") != -1 || context.Request["VFilePath"].IndexOf(".PNG") != -1)

      _path = context.Request.MapPath(context.Request["VFilePath"]);

    else

       

        _path = sNoThumbPath;

     //====================================== 

    System.Drawing.Image image;

    try

    {

 

        image = System.Drawing.Image.FromFile(_path);

    }

    catch (FileNotFoundException e)

    {

        image = System.Drawing.Image.FromFile(sNoThumbPath);

    }

    int srcWidth = image.Width;

    int srcHeight = image.Height;

  

    //      if(srcHeight>srcWidth)

    //      thumbHeight=(srcHeight/srcWidth)*thumbWidth;

    //      else

    //      thumbHeight=(srcWidth/srcHeight)*thumbWidth; 

 

     System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(thumbWidth, (int)thumbHeight); 

 

        //- Create a System.Drawing.Graphics object from the Bitmap which we will use to draw the high quality scaled image

        System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bitmap);

 

        //- Set the System.Drawing.Graphics object property SmoothingMode to HighQuality

        gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

 

        //- Set the System.Drawing.Graphics object property CompositingQuality to HighQuality

        gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

 

        //- Set the System.Drawing.Graphics object property InterpolationMode to High

        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

 

        //- Draw the original image into the target Graphics object scaling to the desired width and height

        System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, (int)thumbHeight);

        //Set Image codec of JPEG type, the index of JPEG codec is "1"

 

        System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1]; 

 

        //Set the parameters for defining the quality of the thumbnail... here it is set to 100%

 

        System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);

 

        eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);

      

        gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, System.Drawing.GraphicsUnit.Pixel);

       

     //====================================== 

}

Save the above ASP.NET file as ThumbnailHandler.ashx.

Now your webpage is ready to shine with great quality thumbnails.

This is how you an use the above ASHX file.

1. For HTML image tag:

<
img src="ThumbnailHandler.ashx?VFilePath=../image/Myimage.jpg & Height=230 & Width=340" alt="Thumbnailimage" />

2. For ASP.NET Image tag:

<
asp:Image id="Image1" runat="server" ImageUrl="ThumbnailHandler.ashx?VFilePath=~/Images/Myimage.jpg  & Height=230 & Width=340" AlternateText="Thumbnailimage" />

I think situation is more clear to you now so start using it and enjoy.

Give feedback to keep my article live.

Login to add your contents and source code to this article
share this article :
post comment
 

Hi, It looks nice article, but as i implement it, it is not working for me. infact I am trying this in asp.Net MVC . but :( please help

Posted by lalit dhake Jan 10, 2011

Hi Amit


here is the mark up call
 <asp:Image ID="imgThumb" runat="server"  ImageUrl="ThumbnailHandler.ashx?VFilePath=~/documents/pF232167k8/test.jpg & Height=230 & Width=340" AlternateText="Thumbnailimage"  />

here is the source for a test image:
<img id="ctl00_CPHContent_rptUploadedDocuments_ctl01_gvDocs_ctl02_imgThumb" src="ThumbnailHandler.ashx?VFilePath=~/documents/pF232167k8/test.jpg &amp; Height=230 &amp; Width=340" alt="Thumbnailimage" style="border-width:0px;" />

I get the standard broken image.

please help
John

Posted by John Hazin Jul 23, 2010

Hi Amit.


Thanks your for help.
how did you register the handler? 
What do I add in the web.config file if anything? or Is it done in IIS 7?

Thanks.
John 

Posted by John Hazin Jul 19, 2010

One more thing?

Do i need to register the handler? 

Thanks

Posted by John Hazin Jul 16, 2010

Hi Amit;


Just as note I tried putting the code in the onmouseover of the hyper link but sadly no luck.

thanks
John

Posted by John Hazin Jul 16, 2010
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Become a Sponsor