We take pride in your success. We let our positivity drive us, day in and out. Talk to us at Mindfire to know us more.

Software Technology Tips

Sometimes we may need to generate the thumbnail size of image dynamically. Suppose one situation:

We have a list view, which shows the uploaded documents, but you need to show the thumbnail size of the images for the image files. But there is one condition: The original image file should not get loaded, because that will make the page heavy.
So, We need to generate the Thumbnail size of image on the fly.

At this point Generic WebHandler will help us. How? Let see...
- Add one class file to your website. and implement IHttpHandler interface.

The class file(ImageToThumbnail.cs) is below.

using System;
using System.Web;
using System.IO;
using System.Drawing;

public class ImageToThumbnail : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string fileFullPath = context.Request.QueryString["location"];
       
        fileFullPath = Path.Combine(context.Request.PhysicalApplicationPath, fileFullPath);
       
        // Resize the image
        using (Image tempImage = new Bitmap(fileFullPath))
        {
            int imageHeight = 50;
            int imageWidth = 50;
           
            // Now make the thumbnail size of image
            using (Image finalImage = tempImage.GetThumbnailImage(imageWidth, imageHeight, new Image.GetThumbnailImageAbort(CancelExecution), IntPtr.Zero))
            {
                finalImage.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
    }

    public bool IsReusable
    {
        get { return true; }
    }

    private bool CancelExecution()
    {
        return false;
    }
}


In the above code:
- IsReusable is a member of IHttpHandler interface that you need to define when you implement IHttpHandler interface.
- GetThumbnailImageAbort is a delegate, which provides a callback method for determining when the  GetThumbnailImage method should prematurely cancel execution. So, you can not put true or false value directly. I have used one function CancelExecution which returns boolean value, to accomplish it.

In Web.config file you nee some modification:
Add one line within the <httpHandlers> </httpHandlers> as <add verb="*" path="ThumbnailConverter.ashx" type="ImageHandler" />

Now this above class will work as a http handler class and you can use it anywhere in your website, where you need to retrieve the thumbnail size of image from a image file.
To show that image put the src as:
ThumbnailConverter.ashx?location=Images_Directory/Image_File_Name.jpg


Related Tags:

ASP. NET, Thumbnail Image, IHttpHandler

Author: Mritunjay Kumar

top

ASP.NET

Let us Connect!

privacy

copyright (c) Mindfire Solutions 2007-2012. Login