Sunday, 6 May 2012

Image Handler in ASP.NET

Step 1) Create  Basic  ASP.NET website  as shown below

 Step 2) select .NET Framework 4.  Choose ASP.NE Empty Web Application

Step3) Add new Generic handler class
            select project-->right click-->Add->New Item then select Generic Handler template as shown below

Step 4)  Name Generic Handler s ImgHandler.cs

Replace ImgHandler.cs with the following content

using System;
using System.Web;

namespace WebApplication3
    public class ImgHandler : IHttpHandler
        /// <summary>
        /// You will need to configure this handler in the web.config file of your
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link:
        /// </summary>
        #region IHttpHandler Members

        public bool IsReusable
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }

        public void ProcessRequest(HttpContext context)
            HttpRequest req=context.Request;
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(context.Server.MapPath(context.Request.FilePath));
            bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            context.Response.ContentType = "image/jpeg";


Step 5) Add Handler to web.config file

        <add verb="*" validate="true" type="WebApplication3.ImgHandler,WebApplication3" path="*.jpg"/>

Step 6)   Add default.aspx page
  then add 

    <form id="form1" runat="server">
     <img src="image1.jpg" alt="img not found" />


Ur handler will be executed.
Note Image should be in root folder of the web application