导入依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
编写kapthca配置类: KaptchaConfig 类
package com.example.demo.config;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.Properties;
@Component
public class KaptchConfig {
@Bean
public DefaultKaptcha getDefaultKaptcha() {
com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
Properties properties = new Properties();
properties.setProperty("kaptcha.border", "no");
properties.setProperty("kaptcha.border.color", "black");
properties.setProperty("kaptcha.border.thickness", "1");
properties.setProperty("kaptcha.image.width", "120");
properties.setProperty("kaptcha.image.height", "60");
properties.setProperty("kaptcha.producer.impl", "com.google.code.kaptcha.impl.DefaultKaptcha");
properties.setProperty("kaptcha.textproducer.impl", "com.google.code.kaptcha.text.impl.DefaultTextCreator");
properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
properties.setProperty("kaptcha.textproducer.char.length", "4");
properties.setProperty("kaptcha.textproducer.font.names", "宋体");
properties.setProperty("kaptcha.textproducer.font.color", "black");
properties.setProperty("kaptcha.textproducer.char.space", "4");
properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.DefaultNoise");
properties.setProperty("kaptcha.noise.color", "blue");
properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.WaterRipple");
properties.setProperty("kaptcha.background.impl", "com.google.code.kaptcha.impl.DefaultBackground");
properties.setProperty("kaptcha.background.clear.to", "white");
properties.setProperty("kaptcha.word.impl", "com.google.code.kaptcha.text.impl.DefaultWordRenderer");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
Controller 层 :
@Resource
DefaultKaptcha defaultKaptcha;
@RequestMapping("/Code")
public ResultVo Code() throws IOException {
String text=defaultKaptcha.createText();
System.out.println("文字验证码为"+text);
ByteArrayOutputStream out = null;
BufferedImage image = defaultKaptcha.createImage(text);
out=new ByteArrayOutputStream();
ImageIO.write(image,"jpg",out);
return ResultVo.success("img",Base64.getEncoder().encodeToString(out.toByteArray()));
}
前端Vue页面
<el-input placeholder="请输入验证码" v-model="user.code">
<template slot="append" class="input_append">
<img src="" alt="" id="codeImg" style="height:34px" @click="getCode()">
</template>
</el-input>