1.maven依赖
<!--验证码框架 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2.控制器 宽度和高度还有颜色可以调节
package com.example.development.config;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.Properties;
/**
* Created with IDEA
* author:QinWei
* Date:2019/4/23
* Time:16:39
* @Description Kaptcha验证码配置
*/
@Component
public class KaptchaConfig {
@Bean
public Producer KaptchaProducer() {
Properties kaptchaProperties = new Properties();
kaptchaProperties.put("kaptcha.border", "no");
kaptchaProperties.put("kaptcha.textproducer.char.length", "4");
kaptchaProperties.put("kaptcha.textproducer.char.space", "6");
kaptchaProperties.put("kaptcha.image.height", "80");
// kaptchaProperties.put("kaptcha.image.width","125");
kaptchaProperties.put("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.WaterRipple");
kaptchaProperties.put("kaptcha.textproducer.font.color", "blue");
kaptchaProperties.put("kaptcha.textproducer.font.size", "60");
//kaptchaProperties.put("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
kaptchaProperties.put("kaptcha.noise.impl", "com.google.code.kaptcha.impl.DefaultNoise");
kaptchaProperties.put("kaptcha.textproducer.char.string", "123456789");
Config config = new Config(kaptchaProperties);
return config.getProducerImpl();
}
}
3.controller
@Autowired
private Producer producer;
@ApiOperation(value = "验证码")
@GetMapping("/captcha.jpg")
public void kaptcha(HttpServletResponse response, HttpSession session) throws IOException {
//生成文字验证码
String code = producer.createText();
//redisService.set(uuid, code);
session.setAttribute("code",code);
response.setHeader("Cache-Control", "no-store,no-cache");
response.setContentType("image/jpeg");
BufferedImage image = producer.createImage(code);
ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(image, "jpg", outputStream);
IOUtils.closeQuietly(outputStream);
}