三行代码生成验证码并转换成base64
发布日期:2021-05-04 20:40:53 浏览次数:29 分类:原创文章

本文共 1583 字,大约阅读时间需要 5 分钟。

使用 Hutool 工具类

import cn.hutool.captcha.CaptchaUtil;import cn.hutool.captcha.LineCaptcha;import cn.hutool.core.io.FileUtil;import cn.hutool.core.lang.Console;import sun.misc.BASE64Encoder;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;/** * Created with IntelliJ IDEA. * * @Auther: zlf * @Date: 2021/04/26/22:40 * @Description: */public class CaptchaTest {       public static void main(String[] args) throws IOException {           //定义图形验证码的长和宽        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);        //图形验证码写出,可以写出到文件,也可以写出到流 写出至文件//        lineCaptcha.write("d:/line.png");////        String code = lineCaptcha.getCode();//        System.out.println("验证码--- " + code);//        //验证图形验证码的有效性,返回boolean值//        boolean verify = lineCaptcha.verify("1234");//        //重新生成验证码//        lineCaptcha.createCode();        // 手动转base64//        File file = FileUtil.touch("d:/line.png");//        FileInputStream inputFile = new FileInputStream(file);//        byte[] buffer = new byte[(int)file.length()];//        inputFile.read(buffer);//        inputFile.close();//        // base64//        String encode = new BASE64Encoder().encode(buffer);//        System.out.println(encode);         // 使用 hutool 工具类        String code  = lineCaptcha.getCode();        String imageBase64 = lineCaptcha.getImageBase64();        System.out.println(imageBase64);    }}

使用场景

当生成验证码后将验证码,以及随机生成的key,保存至redis(验证码作为value),将验证码的base64字符串返回给前端,显示在页面中,用户可以根据识别验证码输入。
<img src="data:image/png;base64,编码code" />

在这里插入图片描述

上一篇:SpringBoot 集成WebSocket
下一篇:求最大公约数和最小公倍数

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年03月30日 18时29分57秒