Create Simple Captcha By Generic Handler

In this post i will create simple captcha image using generic handler.

Create new GenericHandler and write this code snippet

public void ProcessRequest(HttpContext context)
{
        // Create radom number for captcha
      
Random rand = new Random();
       int number = rand.Next(1000, 9999);

       string fontSize = "30";
       Font font = new Font("times new roman", float.Parse(fontSize), FontStyle.Italic);
       Bitmap bitmap = new Bitmap(100,45);
       Graphics graphic = Graphics.FromImage(bitmap);

       // Create hatch brush
       HatchBrush hatchBrush = new HatchBrush(
                  HatchStyle.Sphere,
                  Color.DimGray,
                  Color.LightGray);

       // Fill background with DarkGray color
       graphic.Clear(Color.DarkGray);

       // Drawing random number
       graphic.DrawString(number.ToString(), font, hatchBrush, new PointF(0, 0));
       hatchBrush.Dispose();
       graphic.Dispose();

       // Save image to output stream
       bitmap.Save(context.Response.OutputStream, ImageFormat.Gif);
       bitmap.Dispose();
}
public bool IsReusable
{
       get
       {
               return true;
       }
}

 

Code comments are clear.

for using this snippet in aspx page, you need one line code.

<img src="CaptchaHandler.ashx" />

Result is like this :

 captcha image

Download Demo File


 

No Comments