Monday, 15 April 2013

How to Create a Captcha Control in ASP.NET C#


Client Side Code:-

 <div>
        <asp:Image ID="myImage" runat="server" ImageUrl="~/CaptchaControl.aspx" />
        <br />
        <br />
        Enter code:&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="TextBox1" runat="server" Text=""></asp:TextBox>&nbsp;&nbsp;&nbsp;
        <asp:Button ID="Button1" runat="server" Text="Validate" OnClick="Button1_Click" />
        <br />
        <br />
        <asp:Label ID="lblMessage" runat="server" Font-Bold="true" Font-Size="X-Large" ForeColor="Red"></asp:Label>
    </div>

Server Side Code Description :-

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


public partial class CaptchaControl : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CreateImage();
    }


    private void CreateImage()
    {
        string code = GetRandomText();
        Bitmap bitmap = new Bitmap(200, 150, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        Graphics g = Graphics.FromImage(bitmap);
        Pen pen = new Pen(Color.Yellow);
        Rectangle rect = new Rectangle(0, 0, 200, 150);
        SolidBrush b = new SolidBrush(Color.DarkKhaki);
        SolidBrush blue = new SolidBrush(Color.Blue);
        int counter = 0;
        g.DrawRectangle(pen, rect);
        g.FillRectangle(b, rect);
        Random rand = new Random();
      

        for (int i = 0; i < code.Length; i++)
        {
            g.DrawString(code[i].ToString(), new Font("Verdena", 10 + rand.Next(14, 18)), blue, new PointF(10 + counter, 10));
            counter += 20;
        }

        DrawRandomLines(g);
        Response.ContentType = "image/gif";
        bitmap.Save(Response.OutputStream, ImageFormat.Gif);
        g.Dispose();
        bitmap.Dispose();
    }

    private string GetRandomText()
    {
        StringBuilder randomText = new StringBuilder();
        //if (Session["Code"] == null)
        //{
        string alphabets = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random r = new Random();
        for (int j = 0; j <= 5; j++)
        {
            randomText.Append(alphabets[r.Next(alphabets.Length)]);
        }
        Session["Code"] = randomText.ToString();
        //}
        return Session["Code"] as String;
    }


    private void DrawRandomLines(Graphics g)
    {
        SolidBrush green = new SolidBrush(Color.Green);
        for (int i = 0; i < 20; i++)
        {
            g.DrawLines(new Pen(green, 2), GetRandomPoints());
        }
    }

    private Point[] GetRandomPoints()
    {
        Random rand = new Random();
        Point[] points = { new Point(rand.Next(10, 150), rand.Next(10, 150)), new Point(rand.Next(10, 100), rand.Next(10, 100)) };
        return points;
    }
}



No comments:

Post a Comment