一、引入依赖
//生成验证码的依赖
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
二、配置验证码生成规则
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class KaptchaConfig {
@Bean
public DefaultKaptcha producer() {//验证码生成规则
Properties properties = new Properties();
properties.put("kaptcha.border", "no");
properties.put("kaptcha.textproducer.font.color", "black");
properties.put("kaptcha.textproducer.char.space", "4");
properties.put("kaptcha.image.height", "40");
properties.put("kaptcha.image.width", "120");
properties.put("kaptcha.textproducer.font.size", "30");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
三、生成验证码
@RestController
public class AuthController extends BaseCntroller{
@Autowired
Producer producer;
@RequestMapping("/captcha")
public Map captcha() throws IOException {
String code=producer.createText();//生成验证码
BufferedImage image=producer.createImage(code);//生成验证码图片
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
ImageIO.write(image,"jpg",outputStream);
BASE64Encoder base64Encoder=new BASE64Encoder();
String base64Img=base64Encoder
.encode(outputStream.toByteArray());//转为base64编码
HashMap<String, Object> map = new HashMap<>();
map.put("Img",base64Img);
return map;
);
}