Captcha generate with ASP.NET & C#


Hello all

Today I will demonstrate how to generate captcha with asp.net & C# . though there are many .NET plugin and controls to serve the purpose but my focus is to generate the a random image and its manipulation with the help of .NET framework.

First open a web project and add a "Web user control" , in the example the name of my control is "ImageGeneratorControl.ascx" . the purpose of the control is to generate a image according to the random character.

Now open the  "ImageGeneratorControl.ascx.cs" file (i used the code behind method for the example.) , to generate image we have to use System.Drawing base class.

firstly we have to make a Bitmap type object where the image will generate, then for the texture we have to take a Graphics type object and manipulate the our random string there, after that we will sat the content type and save the Bitmap object stream so that it may  generate a image file, finally we have to dispose our objects.

there is a method named "RandomString" which will take the length of sting to be generate as parameter, in the method i have generate a random number and convert the number into string.In an addition the string will be save in Session.

The code of the  "ImageGeneratorControl.ascx.cs" is as bellow :

using System;
using System.Drawing;

public partial class ImageGeneratorControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Bitmap objBmp = new Bitmap(100, 30);
        Graphics objGraphics ;
        Font objFont = new Font("Arial", 16, FontStyle.Bold);

        objGraphics = Graphics.FromImage(objBmp);
        objGraphics.Clear(Color.WhiteSmoke);

        objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        objGraphics.DrawString(this.RandomString(6), objFont, Brushes.Gray, 3, 3);

        Response.ContentType = "image/GIF";
        objBmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);

        objBmp.Dispose();
        objGraphics.Dispose();
        objFont.Dispose();
    }

    private string RandomString(int length)
    {
        Random rand = new Random();
        char ch;

        System.Text.StringBuilder randString = new System.Text.StringBuilder();

        for(int i = 0 ; i<length; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32((Math.Floor(rand.NextDouble() * 26) + 65)));
            randString.Append(ch);
        }
        Session["CaptchaString"] = randString.ToString().ToLower();
        return randString.ToString().ToLower();    
    }
}

now we have to place that control in a aspx page (we also can handle it with HTTPHandler but for the simplicity i have used a aspx page which will act as a "GIF" image)

so i have taken a Image.aspx file and register the Control as following:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Image.aspx.cs" Inherits="_Image" %>

<%@ Register src="ImageGeneratorControl.ascx" tagname="ImageGeneratorControl" tagprefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<head runat="server">

</head>
<body>
    <form id="form1" runat="server">
      <uc1:ImageGeneratorControl ID="ImageGeneratorControl1" runat="server" />                     
    </form>
</body>

Now this Image.aspx file will act as a Image . What we have to do now is include the Image.aspx page in our main aspx file where the image will be visible. i have used Container.aspx file to generate the captcha as following:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Container.aspx.cs" Inherits="Container" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Captcha Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div><img src="Image.aspx" /></div>
    </form>
</body>
</html>

now you can protect the form from spamming according to your logic,session and image data. 

BYE

, ,

Leave a Reply