java驗證碼 Kaptcha
阿新 • • 發佈:2020-12-15
技術標籤:springbootjava
1.引入依賴
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2.將kaptcha交給spring 容器管理
@Bean
public Producer kaptchaProducer (){
DefaultKaptcha kaptcha = new DefaultKaptcha();
Properties properties = new Properties();
properties.setProperty("kaptcha.image.width","100");
properties.setProperty("kaptcha.image.height","40");
properties.setProperty("kaptcha.textproducer.font.size" ,"40");
properties.setProperty("kaptcha.textproducer.font.color","0,0,0");
properties.setProperty("kaptcha.textproducer.char.string","0123456789QWERTYUIOPASDFGHJKLZXCVBNM");
properties.setProperty("kaptcha.textproducer.char.length" ,"4");
properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
Config config = new Config(properties);
kaptcha.setConfig(config);
return kaptcha;
}
3.使用kaptcha
@RequestMapping("/kaptcha")
public void getKaptcha(HttpServletResponse response, HttpSession session){
String text = producer.createText();
BufferedImage image = producer.createImage(text);
session.setAttribute("kaptcha",text);
response.setContentType("image/png");
try {
ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(image,"png",outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
4.效果