easy-captcha介绍
easy-captcha,提供了Java图形验证码,支持gif、中文、算术等类型,可用于Java Web、JavaSE等项目,是个很好用的工具库,文档比较完备。

用法
添加maven依赖
<!--图形验证码-->
 <dependency>
	  <groupId>com.github.whvcse</groupId>
	  <artifactId>easy-captcha</artifactId>
	  <version>1.6.2</version>
  </dependency>
 
前后端分离时,返回图形验证码的key和图片的base64;
import com.wf.captcha.SpecCaptcha;
/**
    * 获取图形验证码
    *
    * @return
    */
   @RequestMapping(value = "/getCaptcha", method = RequestMethod.GET)
   public Response getCaptcha() {
       final int width = 111;
       final int height = 36;
       String uuid = UUIDUtil.getUUID();
       int len = 4;
       //数字、字母混合的验证码
       final SpecCaptcha captcha = new SpecCaptcha(width, height, len);
       String captchaValue = captcha.text();
       final String captchaKey = getCaptchaKey(uuid);
       log.debug("图形验证码key:{},value:{}", captchaKey, captchaValue);
       //放入redis并设置过期时间
       redisUtil.set(captchaKey, captchaValue, Constants.VERIFYCODE_EXPIRETIME * 60);
       final CaptchaResult captchaResult = new CaptchaResult();
       captchaResult.setCaptchaKey(uuid);
       captchaResult.setImg(captcha.toBase64());
       return captchaResult;
   }
   public class CaptchaResult {
    /**
     * 图形验证码的key
     */
    private String captchaKey;
    /**
     * 图形验证码的base64图片
     */
    private String img;
}
 
提交验证时,将图形验证码的key和图形验证码值一并提交。
测试样例
public class Test {
    
    public static void main(String[] args) {
        // png类型
        SpecCaptcha captcha = new SpecCaptcha(130, 48);
        captcha.text();  // 获取验证码的字符
        captcha.textChar();  // 获取验证码的字符数组
        
        // gif类型
        GifCaptcha captcha = new GifCaptcha(130, 48);
        
        // 中文类型
        ChineseCaptcha captcha = new ChineseCaptcha(130, 48);
        
        // 中文gif类型
        ChineseGifCaptcha captcha = new ChineseGifCaptcha(130, 48);
        
        // 算术类型
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        captcha.setLen(3);  // 几位数运算,默认是两位
        captcha.getArithmeticString();  // 获取运算的公式:3+2=?
        captcha.text();  // 获取运算的结果:5
        captcha.supportAlgorithmSign(2); // 可设置支持的算法:2 表示只生成带加减法的公式
        captcha.setDifficulty(50); // 设置计算难度,参与计算的每一个整数的最大值
        captcha.out(outputStream);  // 输出验证码
        //简单算术类型 SimpleArithmeticCaptcha,用法同ArithmeticCaptcha,只支持加减,计算结果为正整数
    }
}
                

















