如何为jCaptcha生成的Captcha中的文本设置字体样式

时间:2015-08-04 13:15:51

标签: java captcha

我正在使用jcaptcha-all-1.0-RC6生成验证码图像。

相同的代码段位于

之下
          captchaService = new DefaultManageableImageCaptchaService();
          logger.info(" After creating instance  getCaptcha ");
          long id = System.currentTimeMillis();
          String captchaId = String.valueOf(id);

          logger.info(" getCaptcha Id " + captchaId);

          logger.info("***********Coming into captcha service***************************************************");
          BufferedImage challenge = captchaService
                       .getImageChallengeForID(captchaId);
          WritableRaster raster = challenge.getRaster();
        ColorModel model = challenge.getColorModel();
          challenge.setRGB(0,25,51);

          logger.debug("challenge:" + challenge);
          ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

          ImageIO.write(challenge, "jpeg", outputStream);

          outputStream.close();
          outputStream.flush();
          byte[] res = outputStream.toByteArray();

          String encodedImage = Base64.encodeBase64String(res);

然而,我所获得的图像质量并不高质量。我们能做些什么来获得更好的图像质量和更好的可读性。

即使更改字体样式也很有用。任何有关这方面的帮助也很有用

2 个答案:

答案 0 :(得分:3)

要按配置更改图像,您必须扩展ListImageCaptchaEngine并使用Generator:

  • 字词生成器
  • 颜色生成器
  • 背景生成器
  • 字体生成器

    public class MyImageCaptchaEngine extends ListImageCaptchaEngine {
    
    @Override
    protected void buildInitialFactories() {
    
        WordGenerator wgen = new RandomWordGenerator("ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789");
        RandomRangeColorGenerator cgen = new RandomRangeColorGenerator(new int[] { 0, 255 }, new int[] { 20, 100 }, new int[] { 20, 100 });
    
        TextPaster textPaster = new RandomTextPaster(new Integer(4), new Integer(5), cgen, Boolean.TRUE);
    
        BackgroundGenerator backgroundGenerator = new UniColorBackgroundGenerator(new Integer(240), new Integer(50), new Color(252,252,253));
    
    
        Font[] fontsList = new Font[] { new Font("Helvetica", Font.TYPE1_FONT, 10), new Font("Arial", 0, 14), new Font("Vardana", 0, 17), };
    
        FontGenerator fontGenerator = new RandomFontGenerator(new Integer(18), new Integer(30), fontsList);
        WordToImage wordToImage = new ComposedWordToImage(fontGenerator, backgroundGenerator, textPaster);
            this.addFactory(new GimpyFactory(wgen, wordToImage));
        }
    }
    

并使用它

ImageCaptchaService instance = new DefaultManageableImageCaptchaService(
            new FastHashMapCaptchaStore(),
            new MyImageCaptchaEngine(),
            180,
            100000,
            75000);

答案 1 :(得分:1)

请查看DefaultGimpyEngine如何扩展ListImageCaptchaEngine并提供背景颜色,图片大小,字体等设置。(您可以复制并提供自己的值)。

AFAIK字体样式实际上是同一系列的不同字体(例如“Arial bold”和“Arial regular”是“Arial”系列的2种样式)。因此,您只能选择所需的字体(确保它们在系统上可用)。