package com.example.util;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public class CaptchaGenerator {
private static final String CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final int CAPTCHA_LENGTH = 4;
private static final Random random = new Random();
/**
* 获取创建验证码
*/
public static String generateCaptcha() {
StringBuilder captcha = new StringBuilder(CAPTCHA_LENGTH);
for (int i = 0; i < CAPTCHA_LENGTH; i++) {
int index = random.nextInt(CHARACTERS.length());
captcha.append(CHARACTERS.charAt(index));
}
return captcha.toString();
}
/**
* 创建验证码图片
* @param captcha 验证码文本
* @return 验证码图片
*/
public static BufferedImage createCaptchaImage(String captcha) {
int width = 120;
int height = 40;
// 创建图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
// 设置背景色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 设置字体
g.setFont(new Font("Arial", Font.BOLD, 20));
// 绘制验证码
for (int i = 0; i < captcha.length(); i++) {
g.setColor(getRandomColor());
int x = 20 + i * 20;
int y = 25 + random.nextInt(10);
g.drawString(String.valueOf(captcha.charAt(i)), x, y);
}
// 添加干扰线
for (int i = 0; i < 5; i++) {
g.setColor(getRandomColor());
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
g.drawLine(x1, y1, x2, y2);
}
g.dispose();
return image;
}
/**
* 获取随机颜色
* @return 随机颜色
*/
private static Color getRandomColor() {
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
return new Color(r, g, b);
}
}