Pages

Thursday, August 22, 2013

How to Create Captcha in Asp.net

This article we are explaining how to create captcha image or captcha code in asp.net. The Captcha is an acronym based on the word "capture" and standing for "Completely Automated Public Turing test to tell Computers and Humans Apart. Ti implement Captcha image we are using three namespace 'System.Drawing', 'System.Drawing.Imaging' and 'System.Text'.

Step 1
Firstly go in 'Default.aspx' page and add following control. In ImageUrl change your page name. In this example page name is 'CaptchaImg.aspx' so we have added  'CaptchaImg.aspx' in imageUrl.

<form id="form1" runat="server">
        <div>
            <asp:Image ID="ImgCaptcha" runat="server"
                ImageUrl="~/CaptchaImg.aspx" /> <%--change here page name--%>
            <br />
            <br />
            Enter captcha code:
            <asp:TextBox ID="TxtCaptcha" runat="server">
            </asp:TextBox>
            <asp:Button ID="BtnCaptcha" runat="server"
                Text="Validate" OnClick="BtnCaptcha_Click" />
            <br />
            <br />
            <asp:Label ID="lbCaptcha" runat="server" Font-Bold="True"
                Text=""></asp:Label>
        </div>
  </form>

Step 2
In 'Default.aspx.cs' page add following code.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CaptchaImg : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            CreateCaptchaImage();
        }
    }

    private Random rand = new Random();

    private string GetRandomText()
    {
        StringBuilder strRendom = new StringBuilder();
        string alphabets = "abcdefghijklmnoporstuvwxyzABCDEFGHIJKLMNOPQRSTOVWXYZ0123456789";
        Random random = new Random();
        for (int i = 0; i <= 5; i++)
        { strRendom.Append(alphabets[random.Next(alphabets.Length)]); }
        Session["CaptchaCode"] = strRendom.ToString();
        return Session["CaptchaCode"] as String;
    }

    private Point[] GetRandomPoints()
    {
        Point[] points = { new Point(rand.Next(0, 150), rand.Next(1, 150)),
        new Point(rand.Next(0, 200), rand.Next(1, 190)) };
        return points;
    }

    private void DrawRandomLines(Graphics grph)
    {
        SolidBrush lineColor = new SolidBrush(Color.Yellow);
        for (int i = 0; i < 20; i++)
        { grph.DrawLines(new Pen(lineColor, 1), GetRandomPoints()); }
    }

    private void CreateCaptchaImage()
    {
        string code = GetRandomText();
        Bitmap bitmap = new Bitmap(200, 60, System.Drawing.Imaging.PixelFormat.Format48bppRgb);
        Graphics graph = Graphics.FromImage(bitmap);
        Pen penColor = new Pen(Color.YellowGreen);
        Rectangle rect = new Rectangle(0, 0, 200, 75);
        SolidBrush rectColor = new SolidBrush(Color.DarkBlue);
        SolidBrush txtColor = new SolidBrush(Color.WhiteSmoke);
        int counter = 0;
        graph.DrawRectangle(penColor, rect);
        graph.FillRectangle(rectColor, rect);

        for (int i = 0; i < code.Length; i++)
        {
            graph.DrawString(code[i].ToString(),
            new Font("Lucida Handwriting", 10 + rand.Next(15, 20), FontStyle.Italic), txtColor,
            new PointF(10 + counter, 10));
            counter += 28;
        }

        DrawRandomLines(graph);
        bitmap.Save(Response.OutputStream, ImageFormat.Gif);
        graph.Dispose();
        bitmap.Dispose();
    }

    protected void BtnCaptcha_Click(object sender, EventArgs e)
    {
        if (Session["CaptchaCode"] != null && TxtCaptcha.Text == Session["CaptchaCode"].ToString())
        {
            lbCaptcha.ForeColor = Color.Green;
            lbCaptcha.Text = "Captcha code is valide";
        }
        else
        {
            lbCaptcha.ForeColor = Color.Red;
            lbCaptcha.Text = "Captcha code is wrong!!";
        }
    }
}

Step 3

Finally run project.

No comments:

Post a Comment