Simple Example

The complete source code for this example is available in the git repo.

Overview

This is a command line application that generates a few hundred captchas and writes them to separate files. It uses both predefined templates "G" and "Y".

This project contains only one relevant file: App.java. It has a main() method serving as the entry point and a helper method called generate() that does most of the work.

As you can see in the example GCage, YCage (and their ancestor Cage) can be reused. They are thread safe, they can be used as service objects.

An other interesting point is that you can use cage.getTokenGenerator().next() to generate String tokens. You can generate the tokens completely independent from Cage if you want, this method is only supplied for convenience.

cage.draw(String token, OutputStream os) is used to generate an image with the supplied token and write it out in an encoded form to the given output stream. By default jpeg encoding is used.

App.java

public class App {
  public static void main(String[] args) throws IOException {
    generate(new GCage(), 10, "cg1", ".jpg", "colding");
    generate(new YCage(), 10, "cy1", ".jpg", "eT6wLAH");
    generate(new GCage(), 100, "cg2", ".jpg", null);
    generate(new YCage(), 100, "cy2", ".jpg", null);
  }

  protected static void generate(Cage cage, int num, String namePrefix,
      String namePostfix, String text) throws IOException {
    for (int fi = 0; fi < num; fi++) {
      OutputStream os = new FileOutputStream(namePrefix + fi
          + namePostfix, false);
      try {
        cage.draw(
            text != null ? text : cage.getTokenGenerator().next(),
            os);
      } finally {
        os.close();
      }
    }
  }
}