Generating Good Quality Thumbnail Images in ASP.NET


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.


Similar Articles