Spring Boot2.7生成用于登录的图片验证码

先在 pom.xml 注入依赖

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

然后 需要在配置文件中声明一下DefaultKaptcha 的 bean对象
在这里插入图片描述
然后 我们随便找个目录创建一个类 叫CaptchaGenerator.java
专门处理生成验证码的逻辑

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;

@Component
public class CaptchaGenerator {
    
    

    private DefaultKaptcha defaultKaptcha;

    @Autowired
    public CaptchaGenerator(DefaultKaptcha defaultKaptcha) {
    
    
        this.defaultKaptcha = defaultKaptcha;
    }

    public byte[] generateCaptchaImage(String captchaText) throws IOException {
    
    
        Properties properties = new Properties();
        properties.setProperty("kaptcha.textproducer.char.string", "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
        properties.setProperty("kaptcha.textproducer.char.length", "4");

        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);

        BufferedImage captchaImage = defaultKaptcha.createImage(captchaText);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(captchaImage, "jpg", outputStream);

        return outputStream.toByteArray();
    }
}

然后 在写接口的类中 声明一下CaptchaGenerator 的对象
注意 这里要用构造方法赋值
否则东西会拿不到
在这里插入图片描述

private CaptchaGenerator captchaGenerator;

@Autowired
public BookController(CaptchaGenerator captchaGenerator) {
    
    
    this.captchaGenerator = captchaGenerator;
}

最后 编写函数

@GetMapping(value = "/captcha", produces = MediaType.IMAGE_JPEG_VALUE)
public void getCaptchaImage(HttpServletResponse response) throws IOException {
    
    
    String captchaText = "3922";// 生成验证码文本
    byte[] captchaImage = captchaGenerator.generateCaptchaImage(captchaText);

    response.setContentType(MediaType.IMAGE_JPEG_VALUE);
    response.getOutputStream().write(captchaImage);
    response.getOutputStream().flush();
}

在这里插入图片描述

然后 我们直接访问 端口+接口前缀/captcha 即可访问到验证码
在这里插入图片描述
这里 我设置的验证码内容是 3922 你们可以根据情况修改 一般都是随机的

猜你喜欢

转载自blog.csdn.net/weixin_45966674/article/details/133019839