我正在使用 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);
但是我得到的图像质量不是很好。我们可以做些什么来获得更好的图像质量和更好的可读性吗?
甚至更改字体样式也很有用。对此的任何帮助也会很有用
最佳答案
要通过配置更改图像,您必须扩展 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);
关于java - 如何设置 jCaptcha 生成的验证码中文本的字体样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31810395/