验证码工具类
public class ImageVerificationCode {
private static int weight = 100;
private static int height = 47;
private static String text;
private static Random r = new Random();
private static String[] fontNames = {"Georgia"};
private static String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
private static Color randomColor() {
int r = ImageVerificationCode.r.nextInt(225);
int g = ImageVerificationCode.r.nextInt(225);
int b = ImageVerificationCode.r.nextInt(225);
return new Color(r, g, b);
}
private static Font randomFont() {
int index = r.nextInt(fontNames.length);
String fontName = fontNames[index];
int style = r.nextInt(4);
int size = r.nextInt(10) + 24;
return new Font(fontName, style, size);
}
private static char randomChar() {
int index = r.nextInt(codes.length());
return codes.charAt(index);
}
private static void drawLine(BufferedImage image) {
int num = r.nextInt(10);
Graphics2D g = (Graphics2D) image.getGraphics();
for (int i = 0; i < num; i++) {
int x1 = r.nextInt(weight);
int y1 = r.nextInt(height);
int x2 = r.nextInt(weight);
int y2 = r.nextInt(height);
g.setColor(randomColor());
g.drawLine(x1, y1, x2, y2);
}
}
private static BufferedImage createImage() {
BufferedImage image = new BufferedImage(weight, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) image.getGraphics();
g.setColor(new Color(255, 255, r.nextInt(245) + 10));
g.fillRect(0, 0, weight, height);
return image;
}
public static BufferedImage getImage() {
BufferedImage image = createImage();
Graphics2D g = (Graphics2D) image.getGraphics();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++)
{
String s = randomChar() + "";
sb.append(s);
float x = i * 1.0F * weight / 4;
g.setFont(randomFont());
g.setColor(randomColor());
g.drawString(s, x, height - 5);
}
ImageVerificationCode.text = sb.toString();
drawLine(image);
return image;
}
public static String getText() {
return text;
}
public static void output(BufferedImage image, OutputStream out) throws IOException
{
ImageIO.write(image, "JPEG", out);
}
}
前端调用接口,获取验证码
@RequestMapping(value = "/verificationCode",method = RequestMethod.POST)
@ApiOperation("/获取验证码图片")
@CrossOrigin
public ApiResult verificationCode() throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageVerificationCode.output(ImageVerificationCode.getImage(),outputStream);
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String text = ImageVerificationCode.getText();
redisTemplate.opsForValue().set(uuid,text,60, TimeUnit.SECONDS);
byte[] bytes = outputStream.toByteArray();
String encoder = Base64.getEncoder().encodeToString(bytes);
encoder = "data:image/png;base64," + encoder;
Map<String,Object> map = new HashMap<>();
map.put("key",uuid);
map.put("encoder",encoder);
return R.ok(map);
}