三行代码生成验证码并转换成base64
生活随笔
收集整理的這篇文章主要介紹了
三行代码生成验证码并转换成base64
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用 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" />
總結
以上是生活随笔為你收集整理的三行代码生成验证码并转换成base64的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: yum搭建lnmp的最简单方法
- 下一篇: matlab对多个矩阵循环,MATLAB