常见的验证码方案有 kaptcha 等。本篇记录 kaptcha 用法
kaptcha
引入依赖
<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
配置验证码
@Bean
Producer verifyCode() {
Properties properties = new Properties();
// 默认图片样式
properties.put("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.FishEyeGimpy");
// 图片边框
properties.put("kaptcha.border", "yes");
// 文字颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue.
properties.put("kaptcha.textproducer.font.color", "blue");
// 默认图片间隔
properties.put("kaptcha.textproducer.char.space", "5");
// 默认生成图形验证码宽度
properties.put("kaptcha.image.width", "120");
// 默认生成图像验证码高度
properties.put("kaptcha.image.height", "50");
// 验证码文字大小
properties.put("kaptcha.textproducer.font.size", "30");
// 指定字符集
properties.setProperty("kaptcha.textproducer.char.string", "0123456789");
// 指定验证码长度
properties.put("kaptcha.textproducer.char.length", "4");
// 干扰颜色,合法值: r,g,b 或者 white,black,blue
properties.put("kaptcha.noise.color", "blue");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
生成验证码
@Autowired
private CodeService codeService;
@GetMapping("/getCode")
public void code(HttpServletResponse resp) throws IOException {
// MediaType.IMAGE_JPEG_VALUE
resp.setContentType("image/jpeg");
try (ServletOutputStream out = resp.getOutputStream()) {
ImageIO.write(producer.createImage(producer.createText()), "jpg", out);
}
}