Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

SixPack Library -- CaptchaImage

3.29/5 (3 votes)
20 Mar 2009Public Domain1 min read 23K  
SixPack Library tutorial on how to use the CaptchaImage class

Introduction

This article is part of an on-going series of tutorials explaining how to use the SixPack library. In this example, we show how to use the CaptchaImage class to generate effective CAPTCHAs for your site.

Background

About the SixPack Library

The SixPack rapid development library is a collection of classes for rapid development on the .NET/Mono platform. It is released under the Limited General Public License 2.1 (LGPL) and is available through Google code.

Using the Code

This is an example of using the CaptchaImage class in the SixPack library.

Typically, you would generate a random sequence of characters, store it in session, then use this class to serve the image from a handler.

On submit, you would then compare the value input by the user with the value in session.

Stating the obvious: do NOT use a parameter to pass the correct CAPTCHA value to the handler... that would make the CAPTCHA useless!

A not-so-obvious note: mono does not support the WarpPath method in System.Drawing that we use to scramble the text. The class works around this by distorting the image in other ways under Unix environments. This is not as effective as the Win32 method, unfortunately.

In future versions of the library, we might create another CaptchaImage class based on ImageMagick, so we can provide a consistent user experience on both platforms.

C#
using System;
using SixPack.Drawing;
using System.Drawing;
using System.Drawing.Imaging;

namespace sixpackexamples
{
        class MainClass
        {
                public static void Main(string[] args)
                {
                        CaptchaImage captcha = new CaptchaImage
				("foo-bar", 300, 100, "Times New Roman");
                        captcha.BackgroundDark = TangoPalette.SkyBlue1;
                        captcha.BackgroundLight = TangoPalette.SkyBlue3;
                        captcha.ForegroundDark = TangoPalette.SkyBlue2;
                        captcha.ForegroundLight = TangoPalette.SkyBlue1;
                        captcha.FontStyle = FontStyle.Italic;
                        Image image = captcha.Generate();
                        Bitmap bitmap = new Bitmap(image);
                        bitmap.Save("foobar.png", ImageFormat.Png);                    
                }
        }
}

The result of this operation will be the following (under mono):

foobar.png

History

  • 20th March, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication