掌握了思想就可以自定义自己需要的验证码类型,代码写的未优化,不够简洁,如有需要可以自己优化。
算术验证码
// 生成验证码,并提供了转Base64的方法,可以直接给前端使用。
package com.ljwang.http.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;
/**
* @author wlj
* @Classname MathCode
* @Description 算术验证码
* 形式: A opt B = ? 五个字符即可
* @Date 7/30/2022 5:06 PM
*/
public class MathCode {
private static Random random = new Random();
public static String getMathCode() throws IOException {
// 存储结果
String res = "";
// 作出画布
int width = 150;
int height = 60;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 画笔
Graphics2D graphics = (Graphics2D) image.getGraphics();
// 随机画布的颜色
graphics.setColor(new Color(random.nextInt(128,256),random.nextInt(128,256),random.nextInt(128,256)));
graphics.fillRect(0,0,width, height);
// 开始制作图片
// A 0 ~ 9
int optA = random.nextInt(10);
String opts = "+-x";
// B 0 ~ 9
int optB = random.nextInt(10);
String opt = opts.charAt(random.nextInt(opts.