首页 >> 编程知识
图片验证码之hutool生成图片验证码

图片验证码这个工具在现在网站中使用特别多,今天我给大家介绍一款开源工具库,它包含了图片验证码的快速生成代码。
依赖引入
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.39</version> </dependency>
下面是java代码:
1、直线干扰验证码

@GetMapping("/lineCode")
public void lineCode(HttpServletResponse response) throws IOException {
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 5, 20);
response.setContentType("image/png");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 输出图片流
lineCaptcha.write(response.getOutputStream());
}2、圆圈干扰验证码

@GetMapping("/circleCode")
public void circleCode(HttpServletResponse response) throws IOException {
CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(200, 100, 5, 20);
response.setContentType("image/png");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 输出图片流
circleCaptcha.write(response.getOutputStream());
}3、gif验证码

@GetMapping("/gifCode")
public void gifCode(HttpServletResponse response) throws IOException {
GifCaptcha gifCaptcha = CaptchaUtil.createGifCaptcha(200, 100, 5, 1, 0.9f);
response.setContentType("image/gif");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 输出图片流
gifCaptcha.write(response.getOutputStream());
}4、四则运算验证码

private ShearCaptcha shearCaptcha;
@GetMapping("/matchCode")
public void matchCode(HttpServletResponse response) throws IOException {
shearCaptcha = CaptchaUtil.createShearCaptcha(200, 100);
MathGenerator mathGenerator = new MathGenerator();
shearCaptcha.setGenerator(mathGenerator);
response.setContentType("image/png");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 输出图片流
shearCaptcha.write(response.getOutputStream());
}功能特别丰富,你甚至可以自定义一些验证码生成方式,这个就需要大家自己去探索了。
