[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Make CAPTCHA images with overlapping characters in C#

[Make CAPTCHA images with overlapping characters in C#]

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.