Displaying Images in ASP.NET Using HttpHandlers
 
Published: 18 Jul 2007
Abstract
This article explains HttpHandlers and how to use them to display images in ASP.NET.
by Electronic Screw
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 113288/ 1666

Introduction

Most of the time when developing web applications/projects we find the need to display images on the ASP.NET pages. This can include customer pictures, avatars, location maps or other binary data. One good way of doing this is to have a dummy page called, which writes out the binary data using the Response.BinaryWrite() as explained in this article. This article explains using an HttpHandler to display the images.

What is HTTP Handler?

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 useful, though the performance hit is negligible.

Creating an HttpHandler

To create an HttpHandler, we need to implement the IHttpHandler interface. The IHttpHandler contains one property and one method.

Listing 1 - IHttpHandler interface

public interface IHttpHandler 
 {
   bool IsReusable { get; } 
   void ProcessRequest(HttpContext context); 
 }

The property IsReusable specifies whether the ASP.NET should reuse the same instance of the HttpHandler for multiple requests.

The ProcessRequest () method is where you actually implement the logic to handle the request.

After you create the HttpHandler, you have to map a path to the handler in the web.config.

A typical web.config configuration for the handler looks like the following.

Listing 2 - web.config setting for httpHandler

<configuration>
   <system.web>
     ...
     <httpHandlers>
      <add verb="*" path="getAvatarImage.img" type="Sample.ImageHandler, Sample" />
     </httpHandlers>

The verb part is just what you want it to respond to (GET, POST, etc.). Path is the file or file extension you want it to respond to and Type is - ClassName, Assembly. For the above web.config setting, each request to the getAvatarImage.img will be sent to the handler and the ProcessRequest will be executed. When we use a new file extension like "getAvatarImage.img" or "getAvatarImage.do," we need to create IIS extensions mapping for the new extensions.

We will be using the built-in extensions (.ashx) that are already mapped to ASP.NET so that we can avoid the necessity to modify the IIS extensions mapping. With .ashx extension, there is no requirement for registration in the web/machine.config.

HttpHandler to read Images

Now you know what HttpHandlers are and how to setup them, we will write our own httpHandler to read the images from a database. Remember, this article explains creating httpHandler using the generic handler (.ashx). Since the .ashx file extension is already mapped in the IIS to the ASP.NET ISAPI filter, you do not have to configure your web.config file.

Create a new website in Visual Studio 2005. Right-click on the project in the solution explorer and select Add New Item. From the available templates, add the new file of type Generic Handler and name it getImage.ashx

Figure 1 - Create new file of type Generic Handler

Visual Studio 2005 opens a new file with the following content.

Listing 3 - getImage.ashx

<%@ WebHandler Language="C#" Class="getImage" %>
 using System;
 using System.Web;
 
 public class getImage : IHttpHandler {
     
     public void ProcessRequest (HttpContext context) {
         context.Response.ContentType = "text/plain";
         context.Response.Write("Hello World");
     }
 
     public bool IsReusable {
         get  {
             return false;
         }
    }
 }

By default, the IHttpHandler is implemented. We will modify the code in ProcessRequest to read images from database. We are going to use the TableAdapters to read the data from the database.

Listing 4 - Complete getImage.ashx code

<%@ WebHandler Language="C#" Class="getImage"%>
<span style='background:yellow'> </span>
using System;
using System.Web;
using dsImagesTableAdapters;
 
public class getImage : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        int _imageId;
        if (context.Request.QueryString["id"] != null)
            _imageId = Convert.ToInt32(context.Request.QueryString["id"]);
        else
            throw new ArgumentException("No parameter specified");
 
        SampleImagesTableAdapter _adapter = new SampleImagesTableAdapter();
        dsImages.SampleImagesDataTable _imgTable =
            _adapter.GetImageDataById(_imageId);
        
        if (_imgTable.Rows.Count > 0)
        {
            if (_imgTable[0]["Image"] != DBNull.Value)
            {
                context.Response.ContentType = 
                    _imgTable[0]["ImageType"].ToString();
                context.Response.BinaryWrite((byte[])_imgTable[0]["Image"]);
            }
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
 
}

The above code is straightforward and self explanatory. We pass the imageId parameter as a querystring parameter to the getImage.ashx file. If the querystring parameter is null, we throw an ArgumentException as our database method expects an imageId parameter. After that, we are creating a new instance of the tableadapters and call the GetImageDataById method which takes the imageId as a parameter. If the record is found, we write the image content to the response stream using the BinaryWrite method.

The dsImagesTableAdapters comes from the dsImages dataset which is included in the source code.

The first line of the code <%@ WebHandler Language="C#" Class="getImage" %> is a directive syntax which defines the attributes and compilation options for the HTTP Handlers (.ashx) files. This directive is valid only in files used as HTTPHandlers and, by default, ASP.NET treats them as handlers.

For more information check @WebHandler.

Now in your ASP.NET pages, to display the image, we use <img alt="httpHandler" src="getImage.ashx?id=1" > and the image is served through the handler.

Listing 5 - Default.aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<span style='background:yellow'> </span>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <img alt="httpHandler" src="getImage.ashx?id=1">
    </div>
    </form>
</body>

</html>

Now run your application and the page (Default.aspx) displays the image served through HttpHandler.

References

Download

Summary

In this article you have learned how to display images in ASP.NET pages by creating and implementing HttpHandlers with the help of an example.



User Comments

Title: Very Good article   
Name: Jayesh Sorathia
Date: 1/28/2013 2:50:06 AM
Comment:
You can Get Image from Generic HTTP Handler file by implementing HttpHandler interface.
Here is live downloadable C# Examples and VB.Net Examples.
http://jayeshsorathia.blogspot.com/2013/01/net-tips-get-image-from-generic-http-handler-file.html
Title: image display   
Name: S.sreelkshmi
Date: 8/31/2012 3:37:10 AM
Comment:
How to display an image into the web page in asp.net
Title: image display .   
Name: priya
Date: 2/21/2012 10:40:24 AM
Comment:
how to add image in asp.net using vb with ms access oledb connectivity.display, save, retrieve and delete the image.
Title: Prefent lost Image   
Name: Raul
Date: 10/6/2011 3:46:00 PM
Comment:
How to prevent lost image uploaded with ajax upload file control and showded with image Handler on dropdown postback auto postback??
Title: Thanks   
Name: Burak TARHANLI (from Turkey)
Date: 10/4/2011 10:28:21 AM
Comment:
This is an excellent article. Thank you so much.
Title: Question...   
Name: Hans Peter, Denmark
Date: 2/11/2010 2:21:40 AM
Comment:
I have an image saved into a MSSQL Server as varbinary(MAX). How do I get this image and execute it using a handler?

I have found some code here:
[code]
Public Sub getImage()
Dim connectionString As String
Dim connection As SqlConnection
Dim adapter As New SqlDataAdapter
connectionString = "*******"
Dim UserId As String = System.Web.Security.Membership.GetUser().ProviderUserKey.ToString
connection = New SqlConnection(connectionString)

Dim command As New SqlCommand("SELECT Img1 FROM Nomogram WHERE bID=133", connection)
connection.Open()
Dim pictureData As Byte() = DirectCast(command.ExecuteScalar(), Byte())
connection.Close()
Dim picture As Image = Nothing
'Create a stream in memory containing the bytes that comprise the image.
Using stream As New IO.MemoryStream(pictureData)
'Read the stream and create an Image object from the data.
picture = Image.FromStream(stream)
End Using
End Sub
[/CODE]

Any idead on how to display it`?
Kind regards Hans Peter
Title: give the informaion very easy format   
Name: venu
Date: 12/23/2008 9:51:31 AM
Comment:
u will provide the information very easy
Title: Thanks   
Name: Gabriel
Date: 11/27/2008 3:53:58 AM
Comment:
Thanks! That was easy and helpful.
Title: please provide the details of storing images in database using asp.net   
Name: danny
Date: 10/12/2007 9:36:01 AM
Comment:
please provide the same at the earliest
Title: Response to: Missing a Reference for dsImagesTableAdapters?   
Name: Mark
Date: 8/30/2007 9:51:30 AM
Comment:
My bad: I'd put the xsd and xss files in the app_data folder.

Excellent example!
Title: Missing a Reference for dsImagesTableAdapters?   
Name: Mark
Date: 8/30/2007 9:26:30 AM
Comment:
Where do we make the reference to the dsImagesTableAdapters?

thanks
Title: nice   
Name: abc
Date: 8/24/2007 1:30:55 AM
Comment:
nice concept
Title: ASP.NET   
Name: sadat arsalan
Date: 7/21/2007 1:17:42 PM
Comment:
tell me about buttons coding in ASP.NET using HTML codes
Title: Displaying Images in ASP.NET Using HttpHandlers   
Name: Electronic Screw
Date: 7/19/2007 5:34:45 AM
Comment:
Yes, you could do that and the content-type was the "key" to that. I'm writing on that and will be available in a couple of days.

Thanks
Title: Displaying Images in ASP.NET Using HttpHandlers   
Name: Jeff
Date: 7/18/2007 10:50:17 AM
Comment:
Could you use this same sort of set up to pull things like .doc or .pdf files that might be stored in a database?

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2014 ASPAlliance.com  |  Page Processed at 11/27/2014 10:47:14 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search