Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
New MS SQL 2008 Available - DiscountASP.NET
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » GDI+ & Graphics » HTTP Handlers for Images in ASP.NET

HTTP Handlers for Images in ASP.NET

Have you ever thought of streaming thumbnails just by passing query string indicating width or height of thumbnail you need, and most importantly passing those to image itself?

Author Rank:
Technologies: .NET 1.0/1.1, GDI+,Visual C# .NET
Total downloads : 332
Total page views :  33096
Rating :
 5/5
This article has been rated :  3 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ImageHandler.zip
 
ArticleAd
Become a Sponsor



Introduction:

Have you ever thought of streaming thumbnails just by passing query string indicating width or height of thumbnail you need, and most importantly passing those to image itself?

<img src=MyImage.jpg?Height=200> 

Well if you have little knowledge of what HTTP Handlers are, you can do that easily. So what are HTTP handlers?

HTTP Handlers:

HTTP handlers are the .NET components that implement the System.Web.IHttpHandler interface, they can act as a target for the incoming HTTP requests and can be called directly by using their file name in the URL.
HTTP handlers implement the following two methods:
1) ProcessRequest: called to process http requests and 
2) IsReusable which indicates whether this instance of http handler can be reused for fulfilling another requests of the same type.

HTTP handlers can return either true or false in order to specify whether they can be reused.
So lets Create Handler for Images.

Following HttpImageHandler Class Implements IHttpHandler Interface.  

using System;
using System.Web;
using System.IO ;
using System.Drawing;
using System.Drawing.Imaging;
namespace ImageHandler
{
public class HttpImageHandler: IHttpHandler
{
int Width = 0;
int Height = 0;
public void ProcessRequest(System.Web.HttpContext context)
{
if(context.Request.Params["height"] != null)
{
try
{
Height = int.Parse(context.Request.Params["height"]);
}
catch
{
Height = 0;
}
}
if(context.Request.Params["width"] != null)
{
try
{
Width = int.Parse(context.Request.Params["width"]);
}
catch
{
Width = 0;
}
}
if (Width <= 0 && Height <=0)
{
context.Response.Clear();
context.Response.ContentType = getContentType(context.Request.PhysicalPath); context.Response.WriteFile(context.Request.PhysicalPath);
context.Response.End();
}
else
{
context.Response.Clear();
context.Response.ContentType = getContentType(context.Request.PhysicalPath);
byte[] buffer = getResizedImage(context.Request.PhysicalPath,Width,Height);
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
context.Response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
byte[] getResizedImage(String path ,int width,int height)
{
Bitmap imgIn = new Bitmap(path);
double y = imgIn.Height;
double x = imgIn.Width;
double factor = 1;
if(width > 0)
{
factor = width/x;
}
else if (height>0)
{
factor = height/y;
}
System.IO.MemoryStream outStream = new System.IO.MemoryStream();
Bitmap imgOut = new Bitmap((int)(x * factor),(int)(y * factor));
Graphics g = Graphics.FromImage(imgOut);
g.Clear(Color.White);
g.DrawImage(imgIn,new Rectangle(0,0,(int)(factor * x),(int)(factor * y)),new Rectangle(0,0,(int)x,(int)y),GraphicsUnit.Pixel);
imgOut.Save(outStream, getImageFormat(path));
return outStream.ToArray();
}
string getContentType(String path)
{
switch (Path.GetExtension(path))
{
case ".bmp": return "Image/bmp";
case ".gif": return "Image/gif";
case ".jpg": return "Image/jpeg";
case ".png": return "Image/png";
default : break;
}
return "";
}
ImageFormat getImageFormat(String path)
{
switch (Path.GetExtension(path))
{
case ".bmp": return ImageFormat.Bmp;
case ".gif": return ImageFormat.Gif;
case ".jpg": return ImageFormat.Jpeg;
case ".png": return ImageFormat.Png;
default : break;
}
return ImageFormat.Jpeg;
}
}
}

So Whats happening in Code:

1) We are collecting information from Params about width and height required for image.
2) If no height or width is specified then we are streaming file back to user with out doing any thing.
3) If height or width is specified then we are creating resized image in memory and then we are streaming image in memory to client.
4) We also have two methods to getContentType and getImageFormat which are responsible to determining content type and image format necessary for streaming image back to client.

How to Use this Handler in your web application?

Step 1) Compile HttpImageHandler Class into assembly ImageHandler.dll and put that assembly into bin directory of your web application.

Step 2) ASP.NET maintains its configuration information in the machine.config and web.config, for simplicity we will put our information in web.config file.

We can use <httpHandlers> and <add> nodes for adding HTTP handlers to our Web applications.

<httpHandlers>
<add verb="*" path="*.bmp" type="ImageHandler.HttpImageHandler,ImageHandler"/>
<add verb="*" path="*.jpg" type="ImageHandler.HttpImageHandler,ImageHandler"/>
<add verb="*" path="*.gif" type="ImageHandler.HttpImageHandler,ImageHandler"/>
<add verb="*" path="*.png" type="ImageHandler.HttpImageHandler,ImageHandler"/>
</
httpHandlers>

Step 3) we also need to tell IIS about this extension and map it to ASP.NET. If we don't perform this step IIS will simply return image file rather than pass it to ASP.NET runtime. As a result, the HTTP handler will not be called.

Launch the Internet Services Manager tool, right click on Web Site, select Properties, go to Home Directory tab and press Configuration button. This will popup Application Configuration dialog. Click Add button and fill the Executable field with the path to the aspnet_isapi.dll file and fill .jpg in the Extension field. Also change other properties as shown in figure.

Repeat same steps for .bmp, .gif and .png extensions.

Test

Put Image in your application directory and point browser to that image with query string added to it like Http://localhost/yourApplication/yourImage.jpg?Height=200

What more you can do

My examples just shows how to create http handler which can resize image you can easily extend that to perform flips, rotates, change of file type, etc.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Jigar Desai
Jigar Desai is a Microsoft certified professional and has 8 years of experience in Microsoft technologies, he is working in asp.net since pre beta releases and has extensive experience in developing database driven web application. When he is not working with asp.net and SqlServer he likes to do experiments with GDI+ and Content automation in webapplications.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ImageHandler.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
how can i use this for real path.Rakesh5/24/2007
hello sir.. this artical is excellent...but how can i use this for http://www.abc.com/image.jpg when path of image is like this.. then image handler is not working. please help me.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved