follow me

Creating a Captcha image

This time I will talk about a simple captcha image. This will prevent some automated scripts that will spam your registration area in you website, or if you have some comments area in the page.

An overview of the output will be, you will see an image in some part of the page and you will type the text you see in the image in order for you too complete what you are doing.

You need to use the Drawing Assemblies.


using System.Drawing;
using System.Drawing.Text; //for styling fonts
using System.Drawing.Imaging; // for rendering the background


The drawing assemblies are very important because we will draw some random images programmatically.

Now you will need to have a separate page or save it to an image file for the captcha. We will talk about this later.

On the page load event handler of the page, you will have to define the captcha image. The safest way I know is to have a Web user control and place the code inside the page load of the user control and place the user control in any part of the main page. The user control that you place your code shall not have any other controls to prevent disfiguration of the main page.

Ok, on the Page_Load event handler on your user control, you have to initialize the Bitmap.

 
protected void Page_Load(object sender, EventArgs e)
{
// define the Bitmap image with its size.
Bitmap b = new Bitmap(60, 20);
// create a graphics from the initialized bitmap.
Graphics g = Graphics.FromImage(b);
//creates a background color of the image.
g.Clear(Color.Blue);
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;

// ~following codes will be here.
}


You already have initiallize your image. Next is to generate a random alphanumeric characters on the image you just created.



Font f = new Font("Verdana", 8, FontStyle.Bold); // creates an instance of font you will be using.
string randomStr = "";

// initialize all the alphanumeric characters that can be generated on the fly.
string[] str = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q",
"R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y",
"z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };

//generate 5 random alphanumeric characters or depends on how many character you want
Random ar = new Random();

for(int i=0;i$lt;5;i++)
{
string rn = str[ar.Next(0, 62)];
// (0, 62) this means that it will get a random character from str from first character
// to the last and there are 62 characters in all

randomStr += rn; // stack up to randomStr the random characters choosen.
}

g.DrawString(randomStr, f, Brushes.White, 3, 3); // Draw the text to the image.
Response.ContentType = "image/GIF"; // set the image type to GIF.

// save the image into your server path with the filename.
b.Save(Server.MapPath("captcha.gif"), ImageFormat.Gif);



This time you have your alphanumeric characters generated and drawn into the image for later comparison. How can I compare an imge from a text?

Here's how. Remember we stack up the generated random characters into the variable randomStr right? You'll just need to add that string to a session or a cookie. I use session for this example.


// add the randomStr value to a session named "randomStr".
Session.Add("randomStr", randomStr);


Now we're done.

In order to compare the captcha image versus the text the user enters is you have to get the Session value of randomStr.


if(Session["randomStr"].ToString() == txtCaptcha.Text)
{
// your code goes here
}


And here's the complete code.



using System.Drawing;
using System.Drawing.Text; // you need this so you can style your fonts
using System.Drawing.Imaging; // you need this so you can do rendering the background

...

protected void Page_Load(object sender, EventArgs e)
{
Bitmap b = new Bitmap(60, 20); // define the Bitmap image with its size.
Graphics g = Graphics.FromImage(b); // create a graphics from the initialized bitmap.
g.Clear(Color.Blue); // creates a background color of the image.
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;

Font f = new Font("Verdana", 8, FontStyle.Bold); // creates an instance of font you will be using.
string randomStr = "";

// initialize all the alphanumeric characters that can be generated on the fly.
string[] str = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q",
"R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y",
"z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };

// generate 5 random alphanumeric characters
Random ar = new Random();
for(int i=0;i$lt;5;i++)
{
string rn = str[ar.Next(0, 62)];
// (0, 62) this means that it will get a random character from str from first character
// to the last and there are 62 characters in all

randomStr += rn; // stack up to randomStr the random characters choosen.
}

g.DrawString(randomStr, f, Brushes.White, 3, 3); // Draw the text to the image.
Response.ContentType = "image/GIF"; // set the image type to GIF.
b.Save(Server.MapPath("captcha.gif"), ImageFormat.Gif); // save the image into your server path with the filename.
Session.Add("randomStr", randomStr); // add the randomStr value to a session named "randomStr".

// destroys the objects created
f.Dispose();
g.Dispose();
b.Dispose();
}





ciao

0 comments:

Post a Comment