springboot生成验证码图返回前端

1.主要依赖

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

2.配置类

/**
 * 生成验证码的配置
 */
@Configuration
public class CaptchaConfig {
    @Bean
    public Producer CaptchaProducer() {
        Properties properties = new Properties();
        //设置验证码的宽度
        properties.setProperty("kaptcha.image.width", "100");
        //设置宽度
        properties.setProperty("kaptcha.image.height", "40");
        //设置字体大小
        properties.setProperty("kaptcha.textproducer.font.size", "32");
        //设置字体颜色
        properties.setProperty("kaptcha.textproducer.font.color", "0,0,0");
        //限定验证码中的字符
        properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
        //设置验证码的长度
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        //设置添加噪声与否
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
        //将配置装载到一个实例中
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        //将配置传入实例
        defaultKaptcha.setConfig(new Config(properties));
        return defaultKaptcha;
    }

2.控制器 

@RestController
@Api("用户接口")
public class UserController {
@GetMapping(Urls.User.CAPTCHA)
@ApiOperation("请求一个验证码")
public void getCaptcha(HttpServletResponse response, HttpSession session) {
    //    生成验证码
    String text = captchaProducer.createText();
    //    生成验证码图片
    BufferedImage image = captchaProducer.createImage(text);
    //    将图片传入session
    session.setAttribute("captcha", text);
    //    将图片输出到前端(图片+格式)
    response.setContentType("image/png");
    try {
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "png", outputStream);
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("响应验证码失败");
    }
}

}

3.效果 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值