Dynamically Generating Images using ASP.NET Handler
IIS
by default looks for images in files system. But sometime we need to produce
those images dynamically. We can either pre-generate those images or configure
IIS to forward request to our ASP.NET application.
Create
a class that implements IHttpHandler. One can do synchronous or
asynchronous(IHttpAsyncHandler) processing. Implement IsReuseable
property and ProcessRequest(HttpContext) method.
IsResuseable
true means IHttpHandlerFactory will put this IHttpHandler in pool for later use
to improve the performance,
public class GetNameImage : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
Bitmap vImg = new Bitmap(300, 150);
Graphics g = Graphics.FromImage(vImg);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(Color.White);
g.DrawString("Mubbasher Mukhtar",
new Font("Arial", 18),
System.Drawing.Brushes.Black, new PointF(5, 5));
context.Response.ContentType = "image/png";
vImg.Save(context.Response.OutputStream, ImageFormat.Png);
g.Dispose();
vimg.Dispose();
}
public bool IsReusable
{
get
{
return true;
}
}
}
{
public void ProcessRequest (HttpContext context)
{
Bitmap vImg = new Bitmap(300, 150);
Graphics g = Graphics.FromImage(vImg);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(Color.White);
g.DrawString("Mubbasher Mukhtar",
new Font("Arial", 18),
System.Drawing.Brushes.Black, new PointF(5, 5));
context.Response.ContentType = "image/png";
vImg.Save(context.Response.OutputStream, ImageFormat.Png);
g.Dispose();
vimg.Dispose();
}
public bool IsReusable
{
get
{
return true;
}
}
}
Configuring
IIS to forward Image requests to Aspnet_Isapi.dll:
IIS manager click
virtual directory or web site | Directory tab | Click Configuration | Mapping
tab | click Add.
Configuring
ASP.NET to process Image Requests:
Put
the following configuration in web.config: