图形验证码是系统中比较常见的一个功能,网上也有不少现成的解决方案,比如https://gitee.com/whvse/EasyCaptcha。
EasyCaptcha其实已经很方便了,但是它会要在某路径下生成一张实体图片,并且没有返回base64串的实现,本文就是为了解决这两个问题,实现过程中借鉴了EasyCaptcha的部分算法。
设计允许指定验证码的宽、高和字体大小:
#验证码图片高
cw.captcha.width=70
#验证码图片宽
cw.captcha.height=36
#验证码字体大小
cw.captcha.font-size=20
使用Bean来映射这段配置:
@Component
@ConfigurationProperties(prefix = "cw.captcha")
public class CaptchaProperties {
/**
* 验证码宽
*/
private int width;
/**
* 验证码高
*/
private int height;
/**
* 字体大小
*/
private int fontSize;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getFontSize() {
return fontSize;
}
public void setFontSize(int fontSize) {
this.fontSize = fontSize;
}
}
定义一个生成验证码的interface:
public interface CaptchaProcessor {
void generate();
}
实现一下:
@Component
public class CaptchaProcessorImpl implements CaptchaProcessor {
@Autowired
CaptchaProperties captchaProperties;
private static char[] CODE_SEQUENCE = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'

本文介绍了如何在Java中实现图形验证码功能,特别是在EasyCaptcha基础上进行改进,解决了实体图片保存和返回Base64字符串的需求。通过指定验证码的宽度、高度和字体大小,自定义验证码样式,并提供了相关接口的实现。
最低0.47元/天 解锁文章
5759

被折叠的 条评论
为什么被折叠?



