Make CAPTCHA images with overlapping characters in C#

[CAPTCHA]

The following MakeCaptchaImage2 method creates a Bitmap containing a CAPTCHA image.

private Random Rand = new Random();

// 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 = TextRenderingHint.AntiAliasGridFit;

      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;
}

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


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in drawing, graphics, image processing, internet, transformations, web and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *