依赖
<dependency><groupId>com.github.whvcse</groupId><artifactId>easy-captcha</artifactId><version>${easy-captcha.version}</version>
</dependency>
<dependency><groupId>org.openjdk.nashorn</groupId><artifactId>nashorn-core</artifactId><version>${nashorn-core.version}</version>
</dependency>
工具类
public class CaptchaUtil {private static Integer fontSize = 45;private static List<Font> list = new ArrayList<>();static {try {list.add(Font.createFont(Font.TRUETYPE_FONT, Objects.requireNonNull(Captcha.class.getResourceAsStream("/actionj.ttf"))));list.add(Font.createFont(Font.TRUETYPE_FONT, Objects.requireNonNull(Captcha.class.getResourceAsStream("/epilog.ttf"))));
list.add(Font.createFont(Font.TRUETYPE_FONT, Objects.requireNonNull(Captcha.class.getResourceAsStream("/prefix.ttf"))));list.add(Font.createFont(Font.TRUETYPE_FONT, Objects.requireNonNull(Captcha.class.getResourceAsStream("/progbot.ttf"))));
list.add(Font.createFont(Font.TRUETYPE_FONT, Objects.requireNonNull(Captcha.class.getResourceAsStream("/robot.ttf"))));
} catch (FontFormatException | IOException e) {e.printStackTrace();}}public static Captcha getCaptcha(int type, int width, int height, int length) {Captcha captcha;switch (type) {case 1:captcha = new ArithmeticCaptcha(width, height, length);break;case 2:captcha = new ChineseCaptcha(width, height, length);break;case 3:captcha = new ChineseGifCaptcha(width, height, length);break;case 4:captcha = new GifCaptcha(width, height, length);break;case 5: captcha = new SpecCaptcha(width, height, length);break;default:throw new RuntimeException("验证码配置信息错误");}final int index = (int) (Math.random() * list.size());
captcha.setFont(list.get(index).deriveFont(Font.BOLD, fontSize));return captcha;}}
控制器
@RestController
@RequestMapping("/captcha")
public class CaptchaController {@GetMapping("/v1/get")public ResultBean<String> getCaptcha() {final Captcha captcha = CaptchaUtil.getCaptcha(1, 160, 55, 2);System.out.println("验证码对应的文本: "+captcha.text());return captcha.toBase64();}}
效果