SpringBoot图形验证码Kaptcha

引入 pom 依赖

<dependency>
			<groupId>com.github.penggle</groupId>
			<artifactId>kaptcha</artifactId>
			<version>2.3.2</version>
		</dependency>

新建配置类

@Configuration
public class KaptchaConfig {
    @Bean(name = "captchaProducer")
    public DefaultKaptcha getDefaultKaptcha() {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        // 图片边框
        properties.setProperty("kaptcha.border", "no");
        properties.setProperty("kaptcha.border.color", "white");
        properties.setProperty("kaptcha.textproducer.font.color", "255,192,55");
        // 图片宽度
        properties.setProperty("kaptcha.image.width", "125");
        // 图片高度
        properties.setProperty("kaptcha.image.height", "45");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.textproducer.font.size", "38");
        properties.setProperty("kaptcha.noise.color", "21,113,171");
        properties.setProperty("kaptcha.background.clear.from", "0,154,255");
        properties.setProperty("kaptcha.background.clear.to", "0,202,255");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        // 验证码文本字符间距
        properties.setProperty("kaptcha.textproducer.char.space", "5");
        properties.setProperty("kaptcha.textproducer.font.names", "Arial");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

}

生成图形验证码接口

接口返回的是图片 base64 编码,通过在线工具转成图片查看,或前端对接查看效果

public ImageCaptchaVO get() {
        try {
            String captchaToken = UUIDUtils.generateShortUuid();
            String captchaImageCode = defaultKaptcha.createText();
            BufferedImage captchaImage = defaultKaptcha.createImage(captchaImageCode);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(captchaImage, SystemConstants.JPG, outputStream);
            String base64Image = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            RBucket<String> bucket = redissonClient.getBucket(RedissonKeyUtil.getImageCaptchaKey(captchaToken));
            bucket.set(captchaImageCode, systemConfig.getImageCaptchaExpireTime(), TimeUnit.MINUTES);
            return ImageCaptchaVO.newInstance(captchaToken, base64Image);
        } catch (Exception e) {
            log.error("生成验证码异常", e);
            throw new BizException(BizExceptionEnum.IMAGE_CAPTCHA_ERROR);
        }
    }

图形验证码效果

图片Base64互转-支持图片或Base64互相转换-即时工具

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值