java实现生成随机验证码图片

导入库

在Maven仓库搜索kaptcha,将下面的内容拷贝到pom.xml中:

<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

封装配置类

新建KaptchaConfig.java类,

@Configuration				// 该类是配置类
public class KaptchaConfig {
    @Bean
    public Producer kaptchaProducer(){
        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.textproducer.char.impl", 
        	"com.google.code.kaptcha.impl.NoNoise");					// 验证码图片中加什么干扰

        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Config config = new Config();
        kaptcha.setConfig(config);
        return kaptcha;
    }
}

在其他类中调用

    @Autowired							// 注入
    private Producer kaptchaProducer;
    
	@RequestMapping(path = "/kaptcha", method = RequestMethod.GET)	// 请求
    public void getKaptcha(HttpServletResponse response, HttpSession session){
        // 生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);

        // 将验证码存入session
        session.setAttribute("kaptcha", text);

        // 将图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            logger.error("verification code request failed : " + e.getMessage());
        }
    }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值