验证码依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
配置类
@Configuration
public class KaptchaConfig {
@Bean
public Producer kaptcha(){
Properties properties = new Properties();
properties.setProperty("kaptcha.image.width","150");
properties.setProperty("kaptcha.image.height","50");
properties.setProperty("kaptcha.textproducer.char.string","0123456789");
properties.setProperty("kaptcha.textproducer.char.length","4");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
controller层
base64格式
@RestController
public class VerifyController {
@Autowired
Producer producer;
@GetMapping("/code")
public String getVerifyCode(HttpSession session) throws IOException {
String text = producer.createText();
session.setAttribute("kaptcha",text);
System.out.println("=====================>存入session的验证码"+text);
BufferedImage image = producer.createImage(text);
FastByteArrayOutputStream fastByteArrayOutputStream = new FastByteArrayOutputStream();
ImageIO.write(image,"jpg",fastByteArrayOutputStream);
return Base64.getEncoder().encodeToString(fastByteArrayOutputStream.toByteArray());
}
}
图片格式
@GetMapping("/code11")
public void getVerifyCode111(HttpServletResponse response, HttpSession session) throws IOException {
String text = producer.createText();
session.setAttribute("kaptcha",text);
System.out.println("=====================>存入session的验证码"+text);
BufferedImage image = producer.createImage(text);
response.setContentType("image/png");
ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(image,"jpg",outputStream);
}