Make CAPTCHA images with overlapping characters in C#

CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) images are those distorted pictures of words that some Web sites make you enter to prove you are a human and not an automated process. The idea is to distort the characters in the image so it would be hard for an optical character recognition (OCR) application to read them but so it would still be easy for a person to read them.

Note that some scammers outsource CAPTCHA images to cheap labor who get paid around $0.75 per thousand images so this isn't a foolproof technique. However, even that low level of cost is enough to weed out a large percentage of scammers.

The following MakeCaptchaImage2 method creates a Bitmap of the desired size. For each character it measures the character as it will be drawn, picks a random Y coordinate for the character, and draws it. The code then increments the next character's X position by 0.35 times the character's width so the two characters will overlap horizontally.

// Draw the words with letters overlapping each other.
private Bitmap MakeCaptchaImage2(string txt, int wid, int hgt, Font the_font, Brush the_brush)
{
Bitmap bm = new Bitmap(wid, hgt);
using (Graphics gr = Graphics.FromImage(bm))
{
gr.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

Random rand = new Random();
int x = 0;
foreach (char ch in txt.ToCharArray())
{
SizeF ch_size = gr.MeasureString(ch.ToString(), the_font);
int y = (int)(rand.NextDouble() * (hgt - ch_size.Height));
gr.DrawString(ch.ToString(), the_font, the_brush, x, y);
x += (int)(ch_size.Width * 0.35);
}
}

return bm;
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.