import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public class CaptchaGenerator {
private static final String CHAR_SET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private static final int CAPTCHA_LENGTH = 6;
public static String generateCaptchaString() {
Random random = new Random();
StringBuilder captcha = new StringBuilder(CAPTCHA_LENGTH);
for (int i = 0; i < CAPTCHA_LENGTH; i++) {
int index = random.nextInt(CHAR_SET.length());
captcha.append(CHAR_SET.charAt(index));
}
return captcha.toString();
}
private static void addNoise(BufferedImage image) {
Random random = new Random();
int noiseCount = 150;
Graphics2D g2d = image.createGraphics();
for (int i = 0; i < noiseCount; i++) {
int x = random.nextInt(image.getWidth());
int y = random.nextInt(image.getHeight());
int rgb = random.nextInt(0xFFFFFF);
image.setRGB(x, y, rgb);
}
g2d.dispose();
}
private static void addInterferenceLines(BufferedImage image) {
Random random = new Random();
int lineCount = 5;
Graphics2D g2d = image.createGraphics();
for (int i = 0; i < lineCount; i++) {
int x1 = random.nextInt(image.getWidth());
int y1 = random.nextInt(image.getHeight());
int x2 = random.nextInt(image.getWidth());
int y2 = random.nextInt(image.getHeight());
g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g2d.drawLine(x1, y1, x2, y2);
}
g2d.dispose();
}
private static void drawRotatedString(Graphics2D g2d, String text, int x, int y) {
Random random = new Random();
for (char c : text.toCharArray()) {
double angle = (random.nextDouble() - 0.5) * Math.PI / 6; // -30 to 30 degrees
AffineTransform orig = g2d.getTransform();
g2d.rotate(angle, x, y);
g2d.drawString(String.valueOf(c), x, y);
g2d.setTransform(orig);
x += g2d.getFontMetrics().charWidth(c);
}
}
public static BufferedImage generateCaptchaImage(String captchaText) {
int width = 160;
int height = 40;
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedImage.createGraphics();
// 填充背景
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, width, height);
// 设置字体和颜色
g2d.setFont(new Font("Arial", Font.BOLD, 40));
g2d.setColor(Color.BLACK);
// 绘制旋转后的字符串
FontMetrics fontMetrics = g2d.getFontMetrics();
int x = (width - fontMetrics.stringWidth(captchaText)) / 2;
int y = ((height - fontMetrics.getHeight()) / 2) + fontMetrics.getAscent();
drawRotatedString(g2d, captchaText, x, y);
// 添加噪点和干扰线
addNoise(bufferedImage);
addInterferenceLines(bufferedImage);
// 释放图形对象
g2d.dispose();
return bufferedImage;
}
public static void main(String[] args) {
String captchaText = generateCaptchaString();
BufferedImage captchaImage = generateCaptchaImage(captchaText);
// 这里可以将captchaImage保存为文件或在Web应用中输出
}
}