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