Click here to Skip to main content
13,258,878 members (48,997 online)
Click here to Skip to main content
Add your own
alternative version


600 bookmarked
Posted 25 Jan 2004


, 9 Feb 2004
Rate this:
Please Sign up or sign in to vote.
Using CAPTCHA images to prevent automated form submission.

Sample Image - CaptchaImage.gif


CAPTCHA stands for "completely automated public Turing test to tell computers and humans apart." What it means is, a program that can tell humans from machines using some type of generated test. A test most people can easily pass but a computer program cannot.

You've probably encountered such tests when signing up for an online email or forum account. The form might include an image of distorted text, like that seen above, which you are required to type into a text field.

The idea is to prevent spammers from using web bots to automatically post form data in order to create email accounts (for sending spam) or to submit feedback comments or guestbook entries containing spam messages. The text in the image is usually distorted to prevent the use of OCR (optical character reader) software to defeat the process. Hotmail, PayPal, Yahoo and a number of blog sites have employed this technique.

This article demonstrates how to create such an image and employ it within an ASP.NET web form.


You can find more information on CAPTCHA at The CAPTCHA Project and read about its use in foiling purveyors of pills, pr0n and pyramid-schemes in an article from Scientific American entitled Baffling the Bots.

Before using this technique however, you should consider how it will affect your site's accessibility to the blind and other visually impaired visitors. PayPal attempts to address this problem on their sign up form by including a link to an audio file, in which a voice spells out the image text.

The code presented here produces only an image. But, if you had code to generate an audio file, you could easily integrate it.

Using the code

The source code zip file contains the source for one class and two web forms. To use it, just create a new web project and add those items.


  • CaptchaImage.cs - defines the CapchaImage object which actually creates the image.
  • Default.aspx, Default.aspx.cs - a sample web form.
  • JpegImage.aspx, JpegImage.aspx.cs - a web form designed to output a JPEG image rather than HTML.

Let's look at each component and it's purpose.


The CaptchaImage object creates an image given parameters for the text to be displayed, the image dimensions and, optionally, the font to use.

The heart of the code is the GenerateImage() method, shown below, which creates a bitmap image of the specified width and height. This method is called from the CaptchaImage constructor, so the image is ready as soon as you create a new instance of the object.

To create the image, we first fill in the background using a hatched brush (the "dirtier" the image appears, the harder it is for an OCR program to read it).

To make the text fit within the image, we start with an initial font size based on the image height and use the Graphics.MeasureString() method to find the resulting dimensions of the drawn text. If the text exceeds the image dimensions, we reduce the font size and test again and again until a suitable font size is found.

// ====================================================================
// Creates the bitmap image.
// ====================================================================
private void GenerateImage()
  // Create a new 32-bit bitmap image.
  Bitmap bitmap = new Bitmap(

  // Create a graphics object for drawing.
  Graphics g = Graphics.FromImage(bitmap);
  g.SmoothingMode = SmoothingMode.AntiAlias;
  Rectangle rect = new Rectangle(0, 0, this.width, this.height);

  // Fill in the background.
  HatchBrush hatchBrush = new HatchBrush(
  g.FillRectangle(hatchBrush, rect);

  // Set up the text font.
  SizeF size;
  float fontSize = rect.Height + 1;
  Font font;
  // Adjust the font size until the text fits within the image.
    font = new Font(
    size = g.MeasureString(this.text, font);
  } while (size.Width > rect.Width);

  // Set up the text format.
  StringFormat format = new StringFormat();
  format.Alignment = StringAlignment.Center;
  format.LineAlignment = StringAlignment.Center;

  // Create a path using the text and warp it randomly.
  GraphicsPath path = new GraphicsPath();
    (int) font.Style,
    font.Size, rect,
  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);

  // Draw the text.
  hatchBrush = new HatchBrush(
  g.FillPath(hatchBrush, path);

  // Add some random noise.
  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);

  // Clean up.

  // Set the image.
  this.image = bitmap;

Once the font is set, we define a GraphicsPath() which essentially converts the text to a set of lines and curves. This can then be distorted using the GraphicsPath.Warp() method with some randomly generated values. The effect is similar to holding a cardboard sign up by opposite corners and giving it a bit of a twist. The resulting path is drawn onto the image, again using a hatch brush to give it a "dirty" appearance.

To complete the distortion, small blots are randomly painted over the image. You could experiment with other effect to thwart OCRs, but keep in mind that it should still be legible to humans, some of whom may have visual impairments


This is a very simple sample web form that contains only a few basic elements, namely an <IMG> tag for the image, a text box and a "Submit" button.

<form id="Default" method="post" runat="server">
  <img src="JpegImage.aspx"><br>
    <strong>Enter the code shown above:</strong><br>
    <asp:TextBox id="CodeNumberTextBox" runat="server"></asp:TextBox>
    <asp:Button id="SubmitButton" runat="server" Text="Submit">
    <em class="notice">
      (Note: If you cannot read the numbers in the above<br>
      image, reload the page to generate a new one.)</em>
  <p><asp:Label id="MessageLabel" runat="server"></asp:Label></p>

Note that the SRC attribute of the <IMG> tag points to the web form JpegImage.aspx.

The code-behind for Default.aspx simply generates a random text string for the image and validates that this text was entered by the user when the form is submitted. The key is to store the text string in the Session object.

private void Page_Load(object sender, System.EventArgs e)
  if (!this.IsPostBack)

    // Create a random code and store it in the Session object.
    this.Session["CaptchaImageText"] = GenerateRandomCode();

    // On a postback, check the user input.
    if (this.CodeNumberTextBox.Text ==
      // Display an informational message.
      this.MessageLabel.CssClass = "info";
      this.MessageLabel.Text = "Correct!";
      // Display an error message.
      this.MessageLabel.CssClass = "error";
      this.MessageLabel.Text = "ERROR: Incorrect, try again.";

      // Clear the input and create a new random code.
      this.CodeNumberTextBox.Text = "";
      this.Session["CaptchaImageText"] = GenerateRandomCode();

The reason for storing the text string in the Session object is so that it can be accessed by JpegImage.aspx.


For this web form, no HTML is needed (what's there is just the default code generated by Visual Studio when the file was created). Instead of HTML, the code will produce a JPEG image.

In the code-behind, we first create a CaptchaImage object, using the text retrieved from the Session object. This creates a bitmap image for us.

private void Page_Load(object sender, System.EventArgs e)
  // Create a CAPTCHA image using the text stored in the Session object.
  CaptchaImage ci = new CaptchaImage(
    200, 50, "Century Schoolbook");

  // 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.

We then modify the HTTP response headers to set the Content-type to "image/jpeg" so the client browser will know we are sending an image.

The last step is to retrieve the bitmap image from CaptchaImage.Image and write it to the HTTP response output stream in JPEG format. Fortunately, the Save() method of the Bitmap object makes this simple. Any other supported image format could be used as well so long as the Content-type header is set accordingly.

Points of Interest

Because the CaptchaImage class contains a Bitmap object, and bitmaps employ unmanaged resources, a custom Dispose() method is implemented. This allows those unmanaged resources to be freed whenever a CaptchaImage is destroyed.


January 26, 2004 - version 1.0

  • Initial version.

February 2, 2004 - version 1.01

  • Minor fix to correct parameter checking in CaptchaImage.SetDimensions().


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


About the Author

Web Developer
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralRe: Error when building Pin
Etienne6-Mar-08 3:05
memberEtienne6-Mar-08 3:05 
GeneralRe: Error when building Pin
Member 148744330-Apr-08 4:42
memberMember 148744330-Apr-08 4:42 
GeneralRe: Error when building Pin
alize rot25-Nov-08 2:52
memberalize rot25-Nov-08 2:52 
GeneralWell Done Pin
jazzybuzzard11-Sep-07 10:06
memberjazzybuzzard11-Sep-07 10:06 
GeneralRe: Well Done Pin
Beheer2520-Sep-07 9:13
memberBeheer2520-Sep-07 9:13 
Questioni got error Pin
yogarajan ganesan31-Aug-07 0:39
memberyogarajan ganesan31-Aug-07 0:39 
AnswerRe: i got error Pin
Nelson Garcia8-Oct-07 14:32
memberNelson Garcia8-Oct-07 14:32 
Generalcaptcha Pin
marloni28-Aug-07 23:58
membermarloni28-Aug-07 23:58 
AnswerRe: captcha Pin
Tezel Celebi21-Feb-08 13:18
memberTezel Celebi21-Feb-08 13:18 
Generalproblem with image Pin
nebula500022-Aug-07 23:46
membernebula500022-Aug-07 23:46 
GeneralRe: problem with image Pin
Nelson Garcia8-Oct-07 14:36
memberNelson Garcia8-Oct-07 14:36 
QuestionImage still won't show Pin
twinjj22-Aug-07 7:02
membertwinjj22-Aug-07 7:02 
GeneralAdd to Existing cs code Pin
Tango231019-Aug-07 14:54
memberTango231019-Aug-07 14:54 
GeneralMultiple Captcha's Pin
Tango231019-Aug-07 13:57
memberTango231019-Aug-07 13:57 
GeneralThank you Pin
kouelif17-Aug-07 22:53
memberkouelif17-Aug-07 22:53 
GeneralThank you and a question Pin
ketcapli28-Jun-07 12:37
memberketcapli28-Jun-07 12:37 
Generaltest Pin
amitbatra01@gmail.com22-May-07 6:01
memberamitbatra01@gmail.com22-May-07 6:01 
GeneralRe: test Pin
amitbatra01@gmail.com22-May-07 6:02
memberamitbatra01@gmail.com22-May-07 6:02 
Questionvalidation text does not display Pin
scottaday23-Apr-07 11:30
memberscottaday23-Apr-07 11:30 
General2.0 Version Pin
Derrick Roach5-Apr-07 6:03
memberDerrick Roach5-Apr-07 6:03 
GeneralRe: 2.0 Version Pin
arifinsonic16-May-07 20:54
memberarifinsonic16-May-07 20:54 
GeneralRe: 2.0 Version Pin
DZaK835-Aug-07 14:47
memberDZaK835-Aug-07 14:47 
GeneralRe: 2.0 Version Pin
mizzo7-Aug-07 0:30
membermizzo7-Aug-07 0:30 
GeneralCAPTCHA vulnerable to session re-use Pin
bugmenot12312317-Mar-07 8:13
memberbugmenot12312317-Mar-07 8:13 
GeneralRe: CAPTCHA vulnerable to session re-use Pin
ketcapli28-Jun-07 12:38
memberketcapli28-Jun-07 12:38 
GeneralHTTP Error 403 - Forbidden. Pin
here21200723-Feb-07 22:44
memberhere21200723-Feb-07 22:44 
JokeTNX Pin
abbas_keshvari20-Feb-07 21:31
memberabbas_keshvari20-Feb-07 21:31 
General'CaptchaImage' is a 'namespace' but is used like a 'type' Pin
samobeito@hotmail.com20-Feb-07 0:46
membersamobeito@hotmail.com20-Feb-07 0:46 
GeneralRe: 'CaptchaImage' is a 'namespace' but is used like a 'type' Pin
Christian Graus20-Feb-07 1:18
staffChristian Graus20-Feb-07 1:18 
GeneralThe image is not display Pin
quillolander1-Feb-07 8:57
memberquillolander1-Feb-07 8:57 
GeneralRe: The image is not display Pin
kerzhaw7-Feb-07 16:54
memberkerzhaw7-Feb-07 16:54 
GeneralRe: The image is not display Pin
MrBic1-Mar-07 19:59
memberMrBic1-Mar-07 19:59 
GeneralRe: The image is not display Pin
sagarraut9-Mar-07 3:49
membersagarraut9-Mar-07 3:49 
GeneralRe: The image is not display Pin
amitbatra01@gmail.com22-May-07 4:54
memberamitbatra01@gmail.com22-May-07 4:54 
GeneralRe: The image is not display Pin
amitbatra01@gmail.com22-May-07 4:56
memberamitbatra01@gmail.com22-May-07 4:56 
QuestionCan I use the compiled library (.dll) in VB .NET?? Pin
combomatrix31-Jan-07 2:35
membercombomatrix31-Jan-07 2:35 
Generaladapted slightly to DotNet 2.0 Pin
tbhanson29-Nov-06 6:52
membertbhanson29-Nov-06 6:52 
GeneralI'd be interested in your version Pin
Cam Woods4-Dec-06 15:46
memberCam Woods4-Dec-06 15:46 
AnswerRe: I'd be interested in your version Pin
tbhanson4-Dec-06 21:48
membertbhanson4-Dec-06 21:48 
GeneralRe: I'd be interested in your version Pin
JT the Ghost7-Dec-06 5:01
memberJT the Ghost7-Dec-06 5:01 
GeneralRe: I'd be interested in your version Pin
Todd Davis14-Jan-07 7:50
memberTodd Davis14-Jan-07 7:50 
GeneralRe: adapted slightly to DotNet 2.0 Pin
onearth28-Jan-07 5:58
memberonearth28-Jan-07 5:58 
GeneralWarning-help me plz.. =( Pin
ppk8625-Nov-06 22:29
memberppk8625-Nov-06 22:29 
GeneralRe: Warning-help me plz.. =( Pin
cthumann5-Jun-07 6:53
membercthumann5-Jun-07 6:53 
QuestionObject reference not set to an instance of an object Pin
xsoftdev24-Nov-06 14:32
memberxsoftdev24-Nov-06 14:32 
Questionits really helpful Pin
sumit bansal21-Nov-06 1:32
membersumit bansal21-Nov-06 1:32 
AnswerRe: its really helpful Pin
Hint King26-Nov-06 21:50
memberHint King26-Nov-06 21:50 
Generalerror while rewriting the code in Pin
Ravi PM21-Nov-06 1:22
memberRavi PM21-Nov-06 1:22 
Generala control to use it in one shoot Pin
BlaiseBraye20-Nov-06 0:44
memberBlaiseBraye20-Nov-06 0:44 
GeneralCode to generate CAPTCHA Image in PHP Pin
pragyat15-Nov-06 2:53
memberpragyat15-Nov-06 2:53 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171114.1 | Last Updated 10 Feb 2004
Article Copyright 2004 by BrainJar
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid