Amit Choudhary

Amit Choudhary

  • NA
  • 23.4k
  • 5.5m

Generate Good quality Thumbnail images on your website at run time

Oct 9 2009 1:41 AM
Some times we need to show the Thumbnail of a images of big size in our webpages so what we often do just put the height and width of image inside the html and done. but what after the rendering of image blurred, pixeled etc.
But now you can generate the images on the fly using .Net library function to generate the good quality thumbnail.

What you have to do is just create a handler in you asp.net project and put the following code inside the handler.

<%@ 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 it as ThumbnailHandler.ashx ....
Now your webpage is ready to shine with great quality Thumbnail.... ohhh i forget to say how to use it..well use following syntax:

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.

Answers (1)