How To Generate Random Image Using HttpHandler in ASP.NET

How to construct an image generator used to create a visual security code that helps prevent automated sign-ups in your web applications. The text generated is stored in Session to be used for comparison to the user’s input.

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Web.SessionState;

public class Handler : IHttpHandler, IRequiresSessionState
{

   public void ProcessRequest(HttpContext context)
   {
       context.Response.ContentType = "image/gif";
       Bitmap b = new Bitmap(200, 60);
       Graphics g = Graphics.FromImage(b);
       g.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
       Font font = new Font(FontFamily.GenericSansSerif, 48, FontStyle.Bold,
 GraphicsUnit.Pixel);
       Random r = new Random();
       string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
       string letter;
       StringBuilder sb = new StringBuilder();
       for (int x = 0; x < 5; x++)
       {


           letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
           sb.Append(letter);
           g.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15));
       }
       Pen linepen = new Pen(new SolidBrush(Color.Black), 2);
       for (int x = 0; x < 6; x++)
           g.DrawLine(linepen, new Point(r.Next(0, 199), r.Next(0, 59)),
 new Point(r.Next(0, 199), r.Next(0, 59)));
       b.Save(context.Response.OutputStream, ImageFormat.Gif);
       context.Session["image"] = sb;
       context.Response.End();



   }

   public bool IsReusable
   {
       get
       {
           return true;
       }
   }

}

How To Use

<img src="Handler.ashx" alt="Random Image" />

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru