使用 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="https://img-blog.csdnimg.cn/2022010703440731903.png"
/>