Thursday, April 30, 2009

HttpHandler for Displaying Resized images.

How to resize image in asp.net with HttpHandler.

Some time we need to generate Images dynamically and display them on webpage.
In asp.net Using GDI+ we can resize images to fit them in area of our interest. after resizing we can either save them on disk.or can directly display them in webpage.when we display them directly. HttpHandler generate image in memory and send them as response to Client. We can Use asp.net's Image control to display this response directly.

Create GenericHttpHandler Named ImageHandler.ashx and put it in you root directory.
This handler take relative path yof Image and Intended size as input. In response send image with propotional Height and Width. we can Use asp:Image to display this Image.

This Is The Handler to Generate Image.

<%@ WebHandler Language="C#" Class="ImageHandler" %>
using System;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO.Compression;
public class ImageHandler : IHttpHandler
{
//Gets a value indicating whether another request can use the this IHttpHandler instance.
public bool IsReusable
{
get
{
return true;
}
}
public void ProcessRequest(HttpContext context)
{
// Set up the response settings
context.Response.ContentType = "image/jpeg";
context.Response.Cache.SetCacheability(HttpCacheability.Public);
//Gets or sets a value indicating whether to buffer output and send it after the complete page is finished processing.
context.Response.BufferOutput = false;
string PhotoPath = context.Request.QueryString["PhotoPath"] != null ? context.Request.QueryString["PhotoPath"].ToString() : string.Empty;
int Size = context.Request.QueryString["Size"] != null ? Convert.ToInt32(context.Request.QueryString["Size"]) : 0;
if (PhotoPath != string.Empty && Size != 0)
{
PhotoPath = context.Request.QueryString["PhotoPath"];
byte[] b = ResizeImageFile(context.Server.MapPath("~/") + PhotoPath, Size);
context.Response.OutputStream.Write(b, 0, b.Length);
}
else
{
//Throw Exception if Input parameters ar Invalid Or null
throw new Exception("Invalid Parameters");
}
}
public static byte[] ResizeImageFile(string imageFile, int targetSize)
{
using (System.Drawing.Image oldImage = System.Drawing.Image.FromFile(imageFile))
{
Size newSize = CalculateDimensions(oldImage.Size, targetSize);
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
{
using (Graphics canvas = Graphics.FromImage(newImage))
{
canvas.SmoothingMode = SmoothingMode.AntiAlias;
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
MemoryStream Imagememory = new MemoryStream();
newImage.Save(Imagememory, ImageFormat.Png);
return Imagememory.GetBuffer();
}
}
}
}
private static Size CalculateDimensions(Size oldSize, int targetSize)
{
Size newSize = new Size();
if (oldSize.Height > oldSize.Width)
{
newSize.Width = (int)(oldSize.Width * ((float)targetSize / (float)oldSize.Height));
newSize.Height = targetSize;
}
else
{
newSize.Width = targetSize;
newSize.Height = (int)(oldSize.Height * ((float)targetSize / (float)oldSize.Width));
}
return newSize;
}
}



This is How To Use this handler im aspx Page..

<asp:Image ID="imgNew" runat="server" ImageUrl="~/ImageHandler.ashx?PhotoPath=Images/ESNWRedEnvelope.jpg&Size=100" />

Thanks.