java实现生成带颜色的4位随机验证码完整代码
时间: 2024-03-12 07:47:53 浏览: 65
好的,以下是完整的 Java 代码实现生成带颜色的4位随机验证码:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
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 void main(String[] args) {
BufferedImage image = generateCaptcha();
try {
ImageIO.write(image, "PNG", new File("captcha.png")); // 保存验证码到文件
System.out.println("验证码已生成并保存到文件。");
} catch (IOException e) {
e.printStackTrace();
}
}
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;
}
}
```
该代码会在当前目录下生成一个名为 `captcha.png` 的验证码图片文件。你可以使用其他文件格式,如 JPG、GIF 等,只需要将 `ImageIO.write()` 方法的第二个参数改为对应的文件格式即可。
阅读全文