龙空技术网

java验证码生成

大枕头被套 53

前言:

此刻咱们对“java验证码图片生成”都比较注重,兄弟们都想要知道一些“java验证码图片生成”的相关内容。那么小编同时在网络上汇集了一些对于“java验证码图片生成””的相关资讯,希望大家能喜欢,看官们一起来学习一下吧!

依赖导入

<!-- 添加图形验证码依赖 -->

<dependency>

<groupId>cn.hutool</groupId>

<artifactId>hutool-captcha</artifactId>

<version>5.8.5</version>

</dependency>

————————————————

/**

* 生成验证码图片

* @return

*/

@ApiOperation("获取图形验证码")

@GetMapping("/identifyImage")

public Result<String> identifyImage(HttpServletResponse response,

@ApiParam(value = "图形验证码id,无值:生成验证码,有值:刷新验证码")

@RequestParam(name = "codeId", required = false) String codeId) throws IOException {

// 创建验证码,设置宽、高、长度、干扰线数量

LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 90, 4, 100);

// 获取验证码字符串,赋值code

String code = lineCaptcha.getCode();

if (codeId == null) {

// IdWorker.getId():IdWorker工具类生成唯一ID,并转换成String类型

codeId = String.valueOf(IdWorker.getId());

// 将codeId、code.toUpperCase()、过期时间60秒:存储入Redis中

// code.toUpperCase():code装换成大写形式存储

redisOps.set(codeId,code.toUpperCase(),60);

} else {

redisOps.set(codeId,code.toUpperCase(),60);

}

// 将图片验证码codeId设置请求头中

response.setHeader("codeId", codeId);

// 获取向客户端发送响应数据的输出流

try (ServletOutputStream outputStream = response.getOutputStream()) {

// 验证码图片数据写入到输出流

lineCaptcha.write(outputStream);

} catch (Exception e) {

throw new AuthException("图形验证码输出错误");

}

return Result.succ(codeId);

}

————————————————

标签: #java验证码图片生成