生成图片验证码
- 工具类
package com.example.demo.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
public class ValidateCodeUtil {
protected static char[] minCh = new char[]{'0', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
static Random random = new Random();
public static String random(int strLen) {
return random(minCh, strLen);
}
public static String random(char[] charArr, int strLen) {
if (strLen <= 0) {
if (strLen == 0) {
return "";
} else {
throw new IllegalArgumentException();
}
} else {
Random random = new Random();
StringBuilder result = new StringBuilder();
for (int i = 0; i < strLen; ++i) {
int num = random.nextInt(charArr.length);
result.append(charArr[num]);
}
return result.toString();
}
}
private static Color getRandColor() {
Random random = new Random();
Color[] color = new Color[10];
color[0] = new Color(32, 158, 25);
color[1] = new Color(218, 42, 19);
color[2] = new Color(31, 75, 208);
color[3] = new Color(0, 102, 182);
color[4] = new Color(171, 0, 85);
return color[random.nextInt(5)];
}
public static Font getFont() {
Random random = new Random();
Font[] font = new Font[]{new Font("Ravie", 1, 30), new Font("Antique Olive Compact", 1, 30), new Font("Forte", 1, 30), new Font(
"Wide Latin", 1, 30), new Font("Gill Sans Ultra Bold", 1, 30)};
font[5] = new Font("Courier New", 1, 30);
return font[random.nextInt(5)];
}
public static byte[] render(String randomStr, int width, int height) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedImage bi = new BufferedImage(width, height, 13);
Graphics2D g = (Graphics2D) bi.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
g.setFont(new Font("Courier New", 1, 30));
g.setColor(Color.BLACK);
String[] str1 = new String[randomStr.length()];
int i;
int x;
int y;
for (i = 0; i < str1.length; ++i) {
str1[i] = randomStr.substring(i, i + 1);
y = (i + 1) % 3;
if (y == random.nextInt(7)) {
x = 30 - random.nextInt(7);
} else {
x = 30 + random.nextInt(7);
}
g.setColor(getRandColor());
g.drawString(str1[i], 20 * i + 10, x);
}
for (i = 0; i < 100; ++i) {
x = random.nextInt(width);
y = random.nextInt(height);
Color color = new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
g.setColor(color);
g.drawOval(x, y, 0, 0);
}
for (i = 0; i < 15; ++i) {
x = random.nextInt(width);
y = random.nextInt(height);
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
Color color = new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
g.setColor(color);
g.drawLine(x, y, x1, y1);
}
g.dispose();
ImageIO.write(bi, "png", out);
return out.toByteArray();
}
}
- 控制层调用
package com.example.demo.controller;
import com.example.demo.utils.ValidateCodeUtil;
import io.swagger.annotations.ApiOperation;
import org.mapstruct.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
@RestController
@RequestMapping("/qrCode")
public class QRCodeController {
private static final Logger LOGGER = LoggerFactory.getLogger(QRCodeController.class);
@RequestMapping(value = "/generateQRCode", method = RequestMethod.GET)
@ApiOperation("获取图形验证码")
public void generateQRCode(@Context HttpServletRequest request, HttpSession session
, @Context HttpServletResponse response) {
LOGGER.info("generateQRCode session id: {}", session.getId());
try {
String code = ValidateCodeUtil.random(4);
LOGGER.debug("生成的验证码code是:{}", code);
byte[] codeImg = ValidateCodeUtil.render(code, 100, 50);
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
ServletOutputStream sos = response.getOutputStream();
sos.write(codeImg);
sos.flush();
sos.close();
} catch (IOException e) {
LOGGER.error("generateQRCode error : {}", e);
}
}
}
|