SimpleCaptcha
Customizing Your Image CAPTCHAs
While the default implementation of SimpleCaptcha will hopefully provide all your needs straight out-of-the-box, you may find it useful to customize your CAPTCHA. SimpleCaptcha provides hooks allowing you to specify how answers are generated (five Latin characters, from a list of words, etc.), how the answer is rendered on the image, how backgrounds are generated, and so forth.
Image CAPTCHAs are generated using Captcha.Builder
:
1 Captcha captcha = new Captcha.Builder(200, 50) 2 .addText() 3 .build(); // Required! Always!
This will generate a 200×50 image that looks something like this:
Here, the call to addText()
on line 2 uses the default behavior to generate an answer: five random Latin characters. Most of the add*
methods in the Builder
have two versions: a no-arg version which provides default behavior, and another which will allow you to provide your own behavior. For example, in addition to the addText()
method there is an addText(TextProducer)
version. If you had your own TextProducer
, you could use it with the builder like so:
1 Captcha captcha = new Captcha.Builder(200, 50) 2 .addText(new MyTextProducer()) 3 .build();
Arabic and Chinese TextProducers
are provided for you. So if you wanted to generate an answer in Arabic, you would do the following:
1 Captcha captcha = new Captcha.Builder(200, 50) 2 .addText(new ArabicTextProducer()) 3 .build();
Let’s take a look at a more flushed-out implementation of of the Builder
.
1 Captcha captcha = new Captcha.Builder(200, 50) 2 .addText() 3 .addBackground() 4 .addNoise() 5 .gimp() 6 .addBorder() 7 .build(); // Required.
This would yield something like:
Each of the builder methods has a no-args version, and most have one (or more) overloaded versions so you can add your own behavior. Let’s take our last example and make it more customized:
1 Captcha captcha = new Captcha.Builder(200, 50) 2 .addText(new ChineseTextProducer(6)) // Answer will be 6 Chinese characters 3 .addBackground(new GradiatedBackgroundProducer()) 4 .addNoise(new StraightLineNoiseProducer()) 5 .gimp(new FishEyeGimpyRenderer()) 6 .addBorder() 7 .build(); // Required.
Here, each of the methods on lines 2-4 have had non-default types passed to them, and would generate something like this:
Note that the gimp()
, addNoise()
, and addText()
methods can be called multiple times. For example:
1 Captcha captcha = new Captcha.Builder(250, 50) 2 .addBackground(new GradiatedBackgroundProducer()) 3 .addText(new ChineseTextProducer(2)) 4 .addText(new DefaultTextProducer(2)) 5 .addText(new ChineseTextProducer(2)) 6 .gimp() 7 .gimp(new DropShadowGimpyRenderer()) 8 .addNoise() 9 .addNoise() 10 .addNoise() 11 .addBorder() 12 .build(); // Required.
This would generate something like this:
SimpleCaptcha is designed to be easy both to use and extend. Feel free to experiment with it to get the behavior you need for your project