Click here to Skip to main content
15,442,199 members
Articles / Web Development / ASP.NET
Technical Blog
Posted 16 Mar 2011


49 bookmarked

Captcha Image using C# in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.91/5 (32 votes)
22 Mar 2011CPOL2 min read
Captcha Image using C# in ASP.NET

What is Captcha Image?

Source: DotNet Stuff


If both match, then displays the above message:


If both don't match, then display the above message.

In the web, whenever you register on any site, normally they ask at the end of page for entering Image code/Challenge Image/Image verification code, etc. This type of image is called Captcha Image.

What is the Use of Captcha?


Captcha is a type of challenge-response test used in computing to ensure that the response is not generated by a computer. The process usually involves one computer (a server) asking a user to complete a simple test which the computer is able to generate and grade. Because other computers are unable to solve the CAPTCHA, any user entering a correct solution is presumed to be human.

A best technique to restrict automatic form submissions when developing a web page is to add some kind of verification. As per my knowledge, image verification is the best way, it’s also called Captcha image. In this process, dynamically we are creating an image with random string, either string, number or alphanumeric and displaying it on the web page. After that, at the time of form submission, the user is asked to enter the same code in the text box as shown in that image. Once the form is submitted, then we can compare both auto generated value and entered by user because there is no other good way to protect your webworms from spammers (auto submission).

How Can We Do That?

Here is the detailed explanation with code snippets.

This is the default.aspx (partially):

<asp:Label ID="lblmsg" runat="server" Font-Bold="True" 
	ForeColor="Red" Text=""></asp:Label>
         <br />
    <asp:TextBox ID="txtimgcode" 
    <br />
    <asp:Image ID="Image1" 
    runat="server" ImageUrl="~/CImage.aspx"/>
    <br />
    <asp:Button ID="Button1" runat="server" 
    onclick="Button1_Click" Text="Button" />

In the above code, there are three control Label controls to display message whether entered code is matched or not, TextBox to take input from user and Image box to hold an image autogenerated by CImage.aspx page. Before that, we will see default.aspx.cs page code:

protected void Button1_Click(object sender, EventArgs e)
        if (this.txtimgcode.Text == this.Session["CaptchaImageText"].ToString())
            lblmsg.Text = "Excellent.......";
            lblmsg.Text = "image code is not valid.";
        this.txtimgcode.Text = "";

In button’s click event, we are just checking entered value with stored value in session. And we display the appropriate message on the screen.

CImage.aspx Page

Remove all the code except the first line.

The main code is here which is calling a method to generate random number string and passes it to the class file which will generate image with the same string and return it as a JPEG format.

Here are the details of the code:

using System.Drawing.Imaging;
public partial class CImage : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        // Create a random code and store it in the Session object.
        this.Session["CaptchaImageText"] = GenerateRandomCode();
        // Create a CAPTCHA image using the text stored in the Session object.
        RandomImage ci = new RandomImage(this.Session
			["CaptchaImageText"].ToString(), 300, 75);
        // Change the response headers to output a JPEG image.
        this.Response.ContentType = "image/jpeg";
        // Write the image to the response stream in JPEG format.
        ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);
        // Dispose of the CAPTCHA image object.
    // Function to generate random string with Random class.
    private string GenerateRandomCode()
        Random r = new Random();
        string s = "";
        for (int j = 0; j < 5;j++)
            int i = r.Next(3);
            int ch;
            switch (i)
                case 1:
                    ch = r.Next(0, 9);
                    s = s + ch.ToString();
                case 2:
                    ch = r.Next(65, 90);
                    s = s + Convert.ToChar(ch).ToString();
                case 3:
                    ch = r.Next(97, 122);
                    s = s + Convert.ToChar(ch).ToString();
                    ch = r.Next(97, 122);
                    s = s + Convert.ToChar(ch).ToString();
            r.Next(100, 1999);
        return s;

And finally, the code for RandomImage class which generates Image with the help of BitMap class.

//Extra name space
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
public class RandomImage
//Default Constructor 
      public RandomImage(){}
      public string Text
            get { return this.text; }
    public Bitmap Image
        get { return this.image; }
    public int Width
        get { return this.width; }
    public int Height
        get { return this.height; }
//Private variable
    private string text;
    private int width;
    private int height;
    private Bitmap image;
    private Random random = new Random();
    //Methods declaration
    public RandomImage(string s, int width, int height)
          this.text = s;
          this.SetDimensions(width, height);
    public void Dispose()
    protected virtual void Dispose(bool disposing)
        if (disposing)
    private void SetDimensions(int width, int height)
          if (width <= 0)
                throw new ArgumentOutOfRangeException("width", width, 
                    "Argument out of range, must be greater than zero.");
          if (height <= 0)
                throw new ArgumentOutOfRangeException("height", height, 
                    "Argument out of range, must be greater than zero.");
          this.width = width;
          this.height = height;
    private void GenerateImage()
          Bitmap bitmap = new Bitmap
			(this.width, this.height, PixelFormat.Format32bppArgb);
          Graphics g = Graphics.FromImage(bitmap);
          g.SmoothingMode = SmoothingMode.AntiAlias;
          Rectangle rect = new Rectangle(0, 0, this.width, this.height);
          HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti,
              Color.LightGray, Color.White);
          g.FillRectangle(hatchBrush, rect);
          SizeF size;
          float fontSize = rect.Height + 1;
        Font font;
            font = new Font(FontFamily.GenericSansSerif, fontSize, FontStyle.Bold);
                size = g.MeasureString(this.text, font);
          } while (size.Width > rect.Width);
          StringFormat format = new StringFormat();
          format.Alignment = StringAlignment.Center;
          format.LineAlignment = StringAlignment.Center;
          GraphicsPath path = new GraphicsPath();
          //path.AddString(this.text, font.FontFamily, (int) font.Style, 
          //    font.Size, rect, format);
        path.AddString(this.text, font.FontFamily, (int)font.Style, 75, rect, format);
          float v = 4F;
          PointF[] points =
                new PointF(this.random.Next(rect.Width) / v, this.random.Next(
                   rect.Height) / v),
                new PointF(rect.Width - this.random.Next(rect.Width) / v, 
                    this.random.Next(rect.Height) / v),
                new PointF(this.random.Next(rect.Width) / v, 
                    rect.Height - this.random.Next(rect.Height) / v),
                new PointF(rect.Width - this.random.Next(rect.Width) / v,
                    rect.Height - this.random.Next(rect.Height) / v)
          Matrix matrix = new Matrix();
          matrix.Translate(0F, 0F);
          path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);
          hatchBrush = new HatchBrush(HatchStyle.Percent10, Color.Black, Color.SkyBlue);
          g.FillPath(hatchBrush, path);
          int m = Math.Max(rect.Width, rect.Height);
          for (int i = 0; i < (int) (rect.Width * rect.Height / 30F); i++)
                int x = this.random.Next(rect.Width);
                int y = this.random.Next(rect.Height);
                int w = this.random.Next(m / 50);
                int h = this.random.Next(m / 50);
                g.FillEllipse(hatchBrush, x, y, w, h);
          this.image = bitmap;

Happy coding...

This article was originally posted at


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer Working in Ahmedabad, Gujarat, India
India India

I am working as a Software Engineer in Ahmedabad, Gujrat, India.

I have 12+ Years of Experience in Microsoft Technology Like Asp.Net 4.0,
C#,MVC,EntityFramework, Javascript, Crystal Reports, JQuery etc.

Find out more on :

Comments and Discussions

PraiseThank You Pin
Chou Kevin10-Mar-20 20:38
MemberChou Kevin10-Mar-20 20:38 
Questionnice Pin
Member 1247468113-Nov-17 22:40
MemberMember 1247468113-Nov-17 22:40 
Questionissue after published Pin
AhmerRaza3-Jan-17 5:43
professionalAhmerRaza3-Jan-17 5:43 
QuestionSimilar Problem with Production Pin
rlogan309-Feb-16 16:56
Memberrlogan309-Feb-16 16:56 
QuestionRefresh Button, It is possible ? Pin
aspkiddy7-Oct-15 6:51
Memberaspkiddy7-Oct-15 6:51 
Questionprovide refresh button to this captcha code Pin
Member 116750398-May-15 20:21
MemberMember 116750398-May-15 20:21 
QuestionFontSize calculation Pin
ObiWan_MCC16-Feb-15 4:41
MemberObiWan_MCC16-Feb-15 4:41 
QuestionCaptcha Image using C# in ASP.NET Pin
Member 1035818911-Jan-15 23:39
MemberMember 1035818911-Jan-15 23:39 
QuestionConverting this to MVC Pin
Andrew Penny-SectionAfrican Thompson3-Dec-14 4:13
MemberAndrew Penny-SectionAfrican Thompson3-Dec-14 4:13 
QuestionGreat work Pin
MoscowFlyer23-Sep-14 3:24
professionalMoscowFlyer23-Sep-14 3:24 
GeneralVery nice article Pin
noreplay1024-Aug-14 22:53
Membernoreplay1024-Aug-14 22:53 
Questionconverted to vb Pin
miladsaa5-Aug-14 8:37
Membermiladsaa5-Aug-14 8:37 
QuestionImage Size Pin
Parth Tank26-Jul-14 0:04
MemberParth Tank26-Jul-14 0:04 
Questioncaptcha image invalid Pin
Member 93540234-Jul-14 18:47
MemberMember 93540234-Jul-14 18:47 
GeneralMy vote of 1 Pin
Ammar Asjad Raja22-Apr-14 2:10
MemberAmmar Asjad Raja22-Apr-14 2:10 
Questionquestion Pin
Member 998481212-Apr-14 21:09
MemberMember 998481212-Apr-14 21:09 
GeneralCaptcha Pin
Member 1073607710-Apr-14 21:56
MemberMember 1073607710-Apr-14 21:56 
GeneralERROR - Souce code Pin
Natheem Safin5-Apr-14 20:36
MemberNatheem Safin5-Apr-14 20:36 
Questionrefresh Pin
picee25-Jan-14 23:44
Memberpicee25-Jan-14 23:44 
GeneralPerfect Solution for Captch Pin
Suman Zalodiya16-Dec-13 23:40
MemberSuman Zalodiya16-Dec-13 23:40 
Questioncaptcha image doesn't show up Pin
fniles1-Nov-13 3:46
Memberfniles1-Nov-13 3:46 
QuestionI made a video on CAPTCHA CONTROL in ASP.NET C# Pin
Adhiraj Jaryal18-Oct-13 5:15
MemberAdhiraj Jaryal18-Oct-13 5:15 
SuggestionVery nice piece of code; applying a generic handler Pin
Member 103106152-Oct-13 3:08
MemberMember 103106152-Oct-13 3:08 
Questionhow can i get refresh image Pin
Member 1014512026-Jul-13 0:52
MemberMember 1014512026-Jul-13 0:52 
QuestionRefresh Button Pin
Hosseini-Pedram14-Jul-13 1:01
MemberHosseini-Pedram14-Jul-13 1:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.