Sunday, 20 October 2013

How to create captcha image asp.net C#

Leave a Comment
The word CAPTCHA (stand for "Completely Automated Public Turing test to tell Computers and Humans Apart") is a one mechanism that used in web application to determined is user that access the web application is a human or bot. This is because, the captcha contains some word as Image that required users to enter same word in web application form to complete the process.  The captcha also used to prevent bots from automatically access the web page and do some SPAM thing in the web page.

Today i will show tutorial to create Captcha image in asp.net application :

Checklist :
  1. Create one dummy aspx page name "CaptchaImage.aspx".
  2. Create Captcha class name "CaptchaClass.cs".
  3. Create Page dummy to create captcha image name "Captcha.aspx".

The CaptchaImage.aspx page

 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CaptchaImage.aspx.cs" Inherits="Captcha.CaptchaImage" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>



The CaptchaImage.aspx Code Behind

 
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Drawing;

namespace Captcha
{
    public partial class CaptchaImage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CaptchaClass C = new CaptchaClass();
            Bitmap bitmap = C.CreateImage();
        }
    }
}

The CaptchaClass.cs

 
using System;
using System.Collections.Generic;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;

namespace Captcha
{
    public class CaptchaClass
    {
        public Random rand = new Random();
        public Bitmap CreateImage()
        {
            string randomCode = GetRandomText();
            Bitmap bitmap = new Bitmap(200, 150, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            Graphics g = Graphics.FromImage(bitmap);
            Pen pen = new Pen(Color.Gold);
            Rectangle rect = new Rectangle(0, 0, 200, 150);

            SolidBrush b = new SolidBrush(Color.DarkKhaki);
            SolidBrush blue = new SolidBrush(Color.Gray);

            int counter = 0;
            g.DrawRectangle(pen, rect);
            g.FillRectangle(b, rect);

            for (int i = 0; i < randomCode.Length; i++)
            {
                g.DrawString(randomCode[i].ToString(), new Font("Verdana", 10 + rand.Next(14, 18)), blue, new PointF(10 + counter, 10));
                counter += 20;
            }
            DrawRandomLines(g);
            bitmap.Save(HttpContext.Current.Response.OutputStream, ImageFormat.Gif);

            g.Dispose();
            bitmap.Dispose();
            return bitmap;
        }
        public void DrawRandomLines(Graphics g)
        {
            SolidBrush greenLine = new SolidBrush(Color.Green);
            for (int i = 0; i < 20; i++)
            {
                g.DrawLines(new Pen(greenLine, 2), GetRandomPoints());
            }
        }
        public Point[] GetRandomPoints()
        {
            Point[] points = { new Point(rand.Next(10, 150), rand.Next(10, 150)), new Point(rand.Next(10, 100), rand.Next(10, 100)) };
            return points;
        }
        public string GetRandomText()
        {
            StringBuilder randomText = new StringBuilder();
            string alphabets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            
            Random r = new Random();
            for (int j = 0; j <= 5; j++)
            {
                randomText.Append(alphabets[r.Next(alphabets.Length)]);
            }
            HttpContext.Current.Session["Code"] = randomText.ToString();
            return HttpContext.Current.Session["Code"] as String;
        }

    }
}



The Captcha.aspx Page

 
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
    CodeBehind="Captcha.aspx.cs" Inherits="Captcha.Captcha" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Draw Captcha" 
        onclick="Button1_Click" /><br />
    <asp:Image ID="Image1" runat="server" />
</asp:Content>



The Captcha.aspx Code Behind

 
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Captcha
{
    public partial class Captcha : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Image1.ImageUrl = "CaptchaImage.aspx";
            //to check captcha code, you can try check in session 
            // HttpContext.Current.Session["Code"]<-- store value in captcha image
        }
    }
}



The Output



Have a try =)

References 

  1. http://en.wikipedia.org/wiki/CAPTCHA
  2. http://en.wikipedia.org/wiki/Spam_%28electronic%29


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.