WorldofASP.NET : ASP.NET Directory, Tutorial, Hosting, and Source Code
You are 1 of 57 users


WorldofASP.NET >> ASP.NET >> HttpHandlers and HttpModules

Displaying images in ASP.NET using HttpHandlers

This article explains about HttpHandlers and how you can use them to display images in ASP.NET.
Published Date : 03 Sep 2007
Author : James Douglas
Language : VB.NET,C#
Platform : Wins,.NET
Technology : Visual Studio,ASP.NET
Views : 13139
Rating : (2 votes so far)



Introduction

Most of the time when developing web applications/projects we find the need to display images dynamically on the ASP.NET pages. This can include customer pictures or your product pictures. And normally there are two way of storing the pictures on your database. First, stored the images file in the database, and second one would be storing the images binary data inside the database. Most of the database including MSSQL support storing images as binary format.

Retrieving images dynamically from database based on filename can be quite simple. What we normally do is store all the images on certain folder , get the file name from the database, and then set the image server control path based on the filename and path that we get from database.

Retrieving images dynamically from database based the image binary format on the other hand also is simple. You just need to do Response.BinaryWrite,after you have got the data from the database.
In this tutorial, I will show you how to simplify the code of displaying images by using the HttpHandler. By using HTTPHandler, you only need one single line of html code to dynamically find and display your images from database regardless of you are storing the image only or you are storing the image data.

What is HTTPHandler

HttpHandlers are the earliest possible point where we have access to the requests made to the web server (IIS). When a request is made to the web server for an ASP.NET resource (.aspx, .asmx, etc.), the worker process of the ASP.NET creates the right HttpHandler for the request which responds to the request. The default handlers for each request type that ASP.NET handles are set in the machine.config file. For example, all the requests made to ASP.NET (.aspx) pages are handled by System.Web.UI.PageHandlerFactory. So whenever an ASP.NET is requested at the web server, the PageHandlerFactory will fulfill the request.

Why Http Handlers

Almost everything we do in an HttpHandler, we can simply do it in a normal .aspx page. Then why do we need HttpHandlers? First, the HttpHandlers are more reusable and portable than the normal .aspx pages. Since there are no visual elements in an HttpHandler, they can be easily placed into their own assembly and reused from project to project. Second, HttpHandlers are relatively less expensive than the PageHandler. For a page to be processed at the server, it goes through a set of events (onInit, onLoad, etc.), viewstate and postbacks or simply the complete Page Life Cycle. When you really have nothing to do with the complete page life cycle (like displaying images), HttpHandlers are very useful.

Creating an HttpHandler

To create HTTPHandler, your class need to implement IHttpHandler interface and you need to override two methods. The method name is IsReusable and ProcessRequest. HttpHandler has been known with .ashx extension in ASP.NET World.
Now, lets start coding HttpHandler.

Create new ashx file from VisualStudio
<%@ WebHandler Language="C#" Class="getImage" %>using System;using System.Web;using dsImagesTableAdapters;public class DisplayImage: IHttpHandler {
public void ProcessRequest (HttpContext context) {
int iImageId;if (context.Request.QueryString["id"] != null) 
{
iImageId = Convert.ToInt32(context.Request.QueryString["id"]);
}
else {
throw new ArgumentException("No parameter specified");
}
DataSet dsImages = GetDataSetImagesfromDatabase();
DataTable dtImgTable = dsImages.Tables[0];if (dtImgTable .Rows.Count > 0)
{
if (dtImgTable [0]["Image"] != DBNull.Value)
{
context.Response.ContentType = 
dtImgTable [0]["ImageType"].ToString();
context.Response.BinaryWrite((byte[])dtImgTable[0]["Image"]);
}
}
}
public bool IsReusable {
get {
return false;
}
} 

The code above is quite self explanatory. We search  the images data based on the query string passed into the HttpHandler. Please note that the code above assume that we are storing the image binary format into database and thats why we are using Response.BinaryWrite to output the result to client.
You can change the code above by using your own logic.

Now, to use the HttpHandler on your ASP.NET Pages,

<img alt="httpHandler" src="DisplayImage.ashx?id=1">

Conclusion

As you can see from the code sample above, your code is very easy to read if you are using HttpHandler to handle some of the operation on your ASP.NET pages such as displaying images. There are lots more things you can do in HttpHandler to make your code easier to read and maintain. Please leave me a comment if you have any difficulties in understanding the concept of HttpHandler.




    Other Related and Popular Articles :

    Using HttpHandlers and HttpModules in your ASP.NET Websites
    How to use HttpHandlers and HttpModules on your ASP.NET websites and why you need to use them

    ASP.NET HTTP Modules:
    HTTP Modules use to intercept HTTP requests for modifying or utilize HTTP based requests according to need.

    Building HTTP Handler
    knowledge for HTTP handler and HTTP runtime, how to create custom HTTP Handler


    Author Profile : James Douglas

    I work in a Software House Company in Malaysia (Kuala Lumpur) and I am MCP Certified in C# and Web Application course.
    I originally started my programming in Java but later on changed to Microsoft platform because of the simplicity and ease of use.
    I love .NET programming and am doing it almost every day now.

    Click here to view Author Profile


    How would you rate the quality of this content?
    Poor Excellent

    Comments

    #can't load multiple images at the same time
    16 Aug 2010 11:33 by : selmaguzel

    Hi,
    I use httphandler for displaying images. One image can be displayed. But when there are multiple images, only one displays; the cross sign displays instead of others. However, after right clicking on the cross and choose display image, it becomes visible. Could you have any idea?
    Thanks.

    #RbmBinaryImage
    27 Apr 2009 2:59 by : Ramy Mostafa

    The RbmBinaryImage control will help you display images directly from your database. You could bind the Image field directly to the ImageContent property, also you could specify whether you want the display to be as a thumbnail or not and provide the thumbnail size.

    to get it go to http://www.ramymostafa.com/?p=187

    Regards
    Ramy Mostafa

    #error on using http handler for multiple request,
    10 Nov 2008 3:30 by : renuga

    Hi,
    I am working on the project of similar scenario, to display image from a video server, for this I am using HTTP handler, it works fine for a single user, but while trying to access the same site by multiple user, I get"Page cannot be displayed error", can you please help me in this case.
    Thanks,

    Leave New Comments


    Article Content copyright by James Douglas
    Everything else Copyright © by WorldofASP.NET 2010

    Category
    .NET 3.5
    AJAX and ATLAS
    ASP.NET
    C# Programming
    Classic ASP
    Enterprise Systems
    General .NET
    VB.NET Programming
    Announcements
    Earn Cash by writing an article or review
    For more info Click here







    Legend : - Within 3 Days - Within 6 Days - Within 9 Days

    Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap 1 | SiteMap 2 | Link To Us | Contact Us
    © 2002-2010 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
    Our Partners : ASP.NET Web Hosting | ASP Hosting | ASP.NET Hosting | Phone Card | Calling Card |Stock Investing