java如何实现生成带颜色背景的4位验证码
时间: 2024-03-12 09:47:47 浏览: 50
java彩色验证码的生成
生成带颜色背景的4位验证码可以通过 Java 的 Graphics2D 类和 Random 类实现。以下是一个简单的示例代码:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;
public class CaptchaGenerator {
private static final int WIDTH = 80; // 验证码图片宽度
private static final int HEIGHT = 30; // 验证码图片高度
private static final int CODE_LENGTH = 4; // 验证码长度
private static final String CODE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; // 验证码字符集
public static BufferedImage generateCaptcha() {
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) image.getGraphics();
Random random = new Random();
// 生成随机颜色的背景
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g.fillRect(0, 0, WIDTH, HEIGHT);
// 生成验证码
StringBuilder code = new StringBuilder();
for (int i = 0; i < CODE_LENGTH; i++) {
char c = CODE_CHARACTERS.charAt(random.nextInt(CODE_CHARACTERS.length()));
code.append(c);
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
g.drawString(String.valueOf(c), 15 + i * 15, 20);
}
// 添加干扰线
for (int i = 0; i < 5; i++) {
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
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;
}
}
```
调用 `generateCaptcha()` 方法即可生成一个带颜色背景的 4 位验证码的 BufferedImage 对象。你可以通过将其保存到文件或输出到流中来使用它。
阅读全文