原创

kaptcha图片验证码


Kaptcha 简介

Kaptcha 是一个可高度配置的实用验证码生成工具,可自由配置的选项如:

  • 验证码的字体
  • 验证码字体的大小
  • 验证码字体的字体颜色
  • 验证码内容的范围(数字,字母,中文汉字!)
  • 验证码图片的大小,边框,边框粗细,边框颜色
  • 验证码的干扰线
  • 验证码的样式(鱼眼样式、3D、普通模糊、...)
1.导入依赖
        <dependency>
            <groupId>com.github.axet</groupId>
            <artifactId>kaptcha</artifactId>
            <version>0.0.9</version>
        </dependency>
2.配置类
@Configuration
public class KaptchaConfig {

    @Bean
    public DefaultKaptcha producer () {
        Properties propertis = new Properties();
        //图片是否有边框
        propertis.put("kaptcha.border", "no");
        //图片高度
        propertis.put("kaptcha.image.height", "38");
        //图片宽度
        propertis.put("kaptcha.image.width", "150");
        //字体颜色
        propertis.put("kaptcha.textproducer.font.color", "black");
        //字体大小
        propertis.put("kaptcha.textproducer.font.size", "32");
        Config config = new Config(propertis);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);

        return defaultKaptcha;
    }

}
3.代码实现
  @Autowired
    private Producer producer;
    
    @GetMapping("/capthca.jpg")
    public void keptcha(HttpServletResponse resp) throws IOException {
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        req.getSession().setAttribute(KAPTCHA_SESSION_KEY,text);

        resp.setHeader("Cache-Control","no-store, no-cache");
        resp.setContentType("image/jpeg");
        ServletOutputStream outputStream = resp.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
    }
4.测试

Java
  • 作者:刘柄岐
  • 发表时间: 2021-12-01 14:34
  • 版权声明:自由转载-非商用