Click here to Skip to main content
15,176,816 members
Articles / Programming Languages / C#
Technical Blog
Posted 4 Aug 2010

Tagged as


48 bookmarked

Simple CAPTCHA, Create Your Own in C#

Rate me:
Please Sign up or sign in to vote.
4.88/5 (31 votes)
4 Aug 2010CPOL2 min read
Create your own simple captcha in C#

Have you ever wondered how to create a Captcha for your web forms? Well, it's really simple and it won't take more than 100+ lines of code. This sample captcha that I will demonstrate will have random Font Type, Font Style, Font Color, Font Rotation, Background Style and Background Colour. Here are some samples of what this can generate:

Image 1 Image 2 Image 3 Image 4 Image 5 Image 6

Now without too much explanation, here it goes.

Step 1

In your web project, add a Generic Handler that's the file with the .ahsx extension. I'll just use this for this demo for simplicity and also it will compile on demand like a normal aspx file. It's up to you if you want to create a DLL which is better so you can reuse it in any projects you want. To do that, right click on the project on your Solution Explorer.

Image 7

Then choose your file type, in this sample, it's a Generic Handler.

Image 8

Step 2

Once added, you can start coding, here are the sample codes which you can freely copy.

<%@ WebHandler Language="C#" %>
using System;
using System.Web;
using System.Drawing;
using System.IO;
using System.Web.SessionState;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Drawing.Drawing2D;
public class Captcha : IHttpHandler, IReadOnlySessionState
public void ProcessRequest(HttpContext context)
int iHeight = 80;
int iWidth = 190;
Random oRandom = new Random();

int[] aBackgroundNoiseColor = new int[] { 150, 150, 150 };
int[] aTextColor = new int[] { 0, 0, 0 };
int[] aFontEmSizes = new int[] { 15, 20, 25, 30, 35 };

string[] aFontNames = new string[]
 "Comic Sans MS",
 "Times New Roman",
FontStyle[] aFontStyles = new FontStyle[]
HatchStyle[] aHatchStyles = new HatchStyle[]
 HatchStyle.BackwardDiagonal, HatchStyle.Cross, 
	HatchStyle.DashedDownwardDiagonal, HatchStyle.DashedHorizontal,
 HatchStyle.DashedUpwardDiagonal, HatchStyle.DashedVertical, 
	HatchStyle.DiagonalBrick, HatchStyle.DiagonalCross,
 HatchStyle.Divot, HatchStyle.DottedDiamond, HatchStyle.DottedGrid, 
	HatchStyle.ForwardDiagonal, HatchStyle.Horizontal,
 HatchStyle.HorizontalBrick, HatchStyle.LargeCheckerBoard, 
	HatchStyle.LargeConfetti, HatchStyle.LargeGrid,
 HatchStyle.LightDownwardDiagonal, HatchStyle.LightHorizontal, 
	HatchStyle.LightUpwardDiagonal, HatchStyle.LightVertical,
 HatchStyle.Max, HatchStyle.Min, HatchStyle.NarrowHorizontal, 
	HatchStyle.NarrowVertical, HatchStyle.OutlinedDiamond,
 HatchStyle.Plaid, HatchStyle.Shingle, HatchStyle.SmallCheckerBoard, 
	HatchStyle.SmallConfetti, HatchStyle.SmallGrid,
 HatchStyle.SolidDiamond, HatchStyle.Sphere, HatchStyle.Trellis, 
	HatchStyle.Vertical, HatchStyle.Wave, HatchStyle.Weave,
 HatchStyle.WideDownwardDiagonal, HatchStyle.WideUpwardDiagonal, HatchStyle.ZigZag

//Get Captcha in Session
string sCaptchaText = context.Session["Captcha"].ToString();

//Creates an output Bitmap
Bitmap oOutputBitmap = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
Graphics oGraphics = Graphics.FromImage(oOutputBitmap);
oGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;

//Create a Drawing area
RectangleF oRectangleF = new RectangleF(0, 0, iWidth, iHeight);
Brush oBrush = default(Brush);

//Draw background (Lighter colors RGB 100 to 255)
oBrush = new HatchBrush(aHatchStyles[oRandom.Next
	(aHatchStyles.Length-1)], Color.FromArgb((oRandom.Next(100, 255)), 
	(oRandom.Next(100, 255)), (oRandom.Next(100, 255))), Color.White);
oGraphics.FillRectangle(oBrush, oRectangleF);

System.Drawing.Drawing2D.Matrix oMatrix = new System.Drawing.Drawing2D.Matrix();
int i = 0;
for (i = 0; i <= sCaptchaText.Length - 1; i++)
 int iChars = sCaptchaText.Length;
 int x = iWidth / (iChars + 1) * i;
 int y = iHeight / 2;

 //Rotate text Random
 oMatrix.RotateAt(oRandom.Next(-40, 40), new PointF(x, y));
 oGraphics.Transform = oMatrix;

 //Draw the letters with Random Font Type, Size and Color
 sCaptchaText.Substring(i, 1),
 //Random Font Name and Style
 new Font(aFontNames[oRandom.Next(aFontNames.Length - 1)], 
	aFontStyles[oRandom.Next(aFontStyles.Length - 1)]),  
 //Random Color (Darker colors RGB 0 to 100)
 new SolidBrush(Color.FromArgb(oRandom.Next(0, 100), 
	oRandom.Next(0, 100), oRandom.Next(0, 100))),
 oRandom.Next(10, 40)

MemoryStream oMemoryStream = new MemoryStream();
oOutputBitmap.Save(oMemoryStream, System.Drawing.Imaging.ImageFormat.Png);
byte[] oBytes = oMemoryStream.GetBuffer();


public bool IsReusable
 return false;

There is some commented explanation along the way so you won't get lost, but you can still ask me if you really need.

Step 3

Use that Captcha. On your aspx, add the following as an image like such:

<asp:Image ID="imgCaptcha" ImageUrl="Captcha.ashx" runat="server" />

If you noticed, it's like you are using it as an image, this is because it's an image rendered by that handler which you can see on the bottom part of the Captcha code.


Step 4

Assign a text on that captcha on your code behind:

private void SetCaptchaText()
 Random oRandom = new Random();
 int iNumber = oRandom.Next(100000, 999999);
 Session["Captcha"] = iNumber.ToString();

Note: You may notice that I am using only numbers in this regard, this would be easy so users cannot be confused with l and 1, 0 and o, and other similar looking characters.
Note: By setting the session, you are also setting the text to render on the captcha and if you look at the captcha codes, it is in this section.

string sCaptchaText = context.Session["Captcha"].ToString();

Step 5

Compare that value to what the users had keyed into your text box:

if (Session["Captcha"].ToString() != txtCaptcha.Text.Trim())

That's it. Congratulations! You have created your own captcha.

Image 9

Image 10 Image 11 Image 12 Image 13 Image 14 Image 15


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


About the Author

Raymund Macaalay
Technical Lead
New Zealand New Zealand

Comments and Discussions

QuestionCreation of DLL Pin
Member 141144364-Jul-20 8:33
MemberMember 141144364-Jul-20 8:33 
SuggestionIf image will not render in Internet Explorer Pin
Subrat OS18-Apr-17 20:12
professionalSubrat OS18-Apr-17 20:12 
GeneralRe: If image will not render in Internet Explorer Pin
Member 1496593214-Oct-20 21:43
MemberMember 1496593214-Oct-20 21:43 
GeneralRe: If image will not render in Internet Explorer Pin
Subrat OS14-Oct-20 22:05
professionalSubrat OS14-Oct-20 22:05 
GeneralRe: If image will not render in Internet Explorer Pin
Member 1496593214-Oct-20 22:32
MemberMember 1496593214-Oct-20 22:32 
QuestionGracias por el artículo. Pin
Damián Del Castillo8-Jul-15 10:28
MemberDamián Del Castillo8-Jul-15 10:28 
SuggestionInline CAPTCHA refresh option Pin
SpeedDemonSA5-Jun-15 1:50
MemberSpeedDemonSA5-Jun-15 1:50 
QuestionAdd button Refresh captcha Pin
leduong_hatrung6-May-15 2:56
Memberleduong_hatrung6-May-15 2:56 
QuestionUnable to refresh Captcha in update panel Pin
Shelke Amit16-Dec-14 20:16
MemberShelke Amit16-Dec-14 20:16 
QuestionImage not showing!! Pin
Member 1108337715-Sep-14 2:54
MemberMember 1108337715-Sep-14 2:54 
QuestionRefresh Button Pin
esmael taher13-Oct-13 1:01
Memberesmael taher13-Oct-13 1:01 
SuggestionGood but needs some improvements Pin
midix10-Jul-13 7:36
Membermidix10-Jul-13 7:36 
GeneralMy vote of 5 Pin
Bhoomi Gajjar27-Jun-13 23:55
MemberBhoomi Gajjar27-Jun-13 23:55 
QuestionImage not getting refreshed Pin
wonder-FOOL4-Jun-13 3:06
Memberwonder-FOOL4-Jun-13 3:06 
QuestionWhere is the noise coming from? Pin
slbentley15-May-13 4:59
Memberslbentley15-May-13 4:59 
AnswerRe: Where is the noise coming from? Pin
slbentley15-May-13 6:18
Memberslbentley15-May-13 6:18 
GeneralRe: Where is the noise coming from? Pin
AdamWhitehat4-Jul-13 20:30
professionalAdamWhitehat4-Jul-13 20:30 
SuggestionPlease set the content type before writing image; your browser will like you Pin
Arjan Pot4-Nov-12 21:36
MemberArjan Pot4-Nov-12 21:36 
GeneralRe: Please set the content type before writing image; your browser will like you Pin
jaspadee11-Jan-13 3:47
Memberjaspadee11-Jan-13 3:47 
GeneralMy vote of 5 Pin
james337072-Oct-12 5:20
Memberjames337072-Oct-12 5:20 
GeneralMy vote of 5 Pin
Farhan Ghumra17-Aug-12 1:08
professionalFarhan Ghumra17-Aug-12 1:08 
GeneralMy vote of 4 Pin
johannesnestler25-Jul-12 4:12
Memberjohannesnestler25-Jul-12 4:12 
QuestionHave any tips? Pin
Everson SB11-Jun-12 14:17
MemberEverson SB11-Jun-12 14:17 
GeneralImage not showing Pin
Chain_reaction10-Jan-11 10:41
MemberChain_reaction10-Jan-11 10:41 
GeneralError Pin
lazybit2-Oct-10 2:13
Memberlazybit2-Oct-10 2:13 

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.