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: http://go.microsoft.com/?linkid=8101007
        /// </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";
           
            bmp.Dispose();
        }

        #endregion
    }
}

Step 5) Add Handler to web.config file

<System.Web>
<httpHandlers>
        <add verb="*" validate="true" type="WebApplication3.ImgHandler,WebApplication3" path="*.jpg"/>
      </httpHandlers>
    </system.web>
</System.Web>


Step 6)   Add default.aspx page
  then add 

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

    </div>
    </form>
</body

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