后端实现图片验证码接口
在配置文件夹中新建 Code 配置类
package com.abin.config.captcha;
//封装生成验证码的工具类
public class Code {
private static char code[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2',
'3', '4', '5', '6', '7', '8', '9'};
private static final int WIDTH = 115;
private static final int HEIGHT = 20;
private static final int LENGTH = 4;
public static String getCode(HttpServletRequest request,
HttpServletResponse response){
// TODO Auto-generated method stub
// 设置响应报头信息
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 设置响应的MIME类型
response.setContentType("image/jpeg");
BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
Font mFont = new Font("Arial", Font.TRUETYPE_FONT, 20);
Graphics g = image.getGraphics();
Random rd = new Random();
// 设置背景颜色
g.setColor(new Color(rd.nextInt(55) + 200, rd.nextInt(55) + 200, rd
.nextInt(55) + 200));
g.fillRect(0, 0, WIDTH, HEIGHT);
// 设置字体
g.setFont(mFont);
// 画边框
g.setColor(Color.black);
g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);
// 随机产生的验证码
String result = "";
for (int i = 0; i < LENGTH; ++i) {
result += code[rd.nextInt(code.length)];
}
HttpSession session = request.getSession();
session.setMaxInactiveInterval(2*3600);//session 保存俩小时
// 画验证码
for (int i = 0; i < result.length(); i++) {
g.setColor(new Color(rd.nextInt(200), rd.nextInt(200), rd
.nextInt(200)));
g.drawString(result.charAt(i) + "", (i * 20) + 17, 16);
}
// 随机产生2个干扰线
for (int i = 0; i < 4; i++) {
g.setColor(new Color(rd.nextInt(200), rd.nextInt(200), rd
.nextInt(200)));
int x1 = rd.nextInt(WIDTH);
int x2 = rd.nextInt(WIDTH);
int y1 = rd.nextInt(HEIGHT);
int y2 = rd.nextInt(HEIGHT);
g.drawLine(x1, y1, x2, y2);
}
// 释放图形资源
g.dispose();
try {
OutputStream os = response.getOutputStream();
// 输出图像到页面
ImageIO.write(image, "JPEG", os);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
controller类:
/**
* 验证码
*/
@Controller
public class CaptchaController {
static String code ;
@RequestMapping("/captcha")
public void getImg(HttpServletRequest request, HttpServletResponse response) {
code = Code.getCode(request, response);
request.getSession().setAttribute("captcha",code);
}
}
效果:
也可以:
配置类:
/**
* 验证码的配置类
*/
@Configuration
public class CaptchaConfig {
@Bean
public DefaultKaptcha defaultKaptcha() {
//验证码生成器
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
//配置
Properties properties = new Properties();
//是否有边框
properties.setProperty("kaptcha.border", "yes");
//设置边框颜色
properties.setProperty("kaptcha.border.color", "105,179,90");
//边框粗细度,默认为1
// properties.setProperty("kaptcha.border.thickness","1");
//验证码
properties.setProperty("kaptcha.session.key", "code");
//验证码文本字符颜色 默认为黑色
properties.setProperty("kaptcha.textproducer.font.color", "blue");
//设置字体样式
properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅 黑");
//字体大小,默认40
properties.setProperty("kaptcha.textproducer.font.size", "30");
//验证码文本字符内容范围 默认为abced2345678gfynmnpwx
// properties.setProperty("kaptcha.textproducer.char.string", "");
//字符长度,默认为5
properties.setProperty("kaptcha.textproducer.char.length", "4");
//字符间距 默认为2
properties.setProperty("kaptcha.textproducer.char.space", "4");
//验证码图片宽度 默认为200
properties.setProperty("kaptcha.image.width", "100");
//验证码图片高度 默认为40
properties.setProperty("kaptcha.image.height", "40");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
controller:
/**
* 验证码
*/
@RestController
@RequestMapping("/api")
public class CaptchaController {
@Autowired
private DefaultKaptcha defaultKaptcha;
@ApiOperation(value = "验证码")
@GetMapping(value = "/captcha", produces = "image/jpeg")
public void capacha(HttpServletRequest request, HttpServletResponse response) {
// 定义response输出类型为image/jpeg类型
response.setDateHeader("Expires", 0);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
// return a jpeg
response.setContentType("image/jpeg");
//-------------------生成验证码 begin --------------------------
// 获取验证码的文本内容
String text = defaultKaptcha.createText();
System.out.println("验证码:" + text);
// 将验证码放到session
request.getSession().setAttribute("captcha", text);
// 根据文本验证码内容创建图形验证码
BufferedImage image = defaultKaptcha.createImage(text);
ServletOutputStream servletOutputStream = null;
try {
servletOutputStream = response.getOutputStream();
// 输出流输出图片, 格式为jpg
ImageIO.write(image, "jpg", servletOutputStream);
// 发送到浏览器
servletOutputStream.flush();
}catch (IOException e) {
e.printStackTrace();
}finally {
if (servletOutputStream != null) {
try {
servletOutputStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
//-------------------生成验证码 end ----------------------------
}
}
预览效果: