写一段java生成验证码的代码案例
时间: 2024-05-01 10:18:38 浏览: 84
Sure! 以下是一段使用Java生成验证码的代码案例:
```
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
public class CaptchaGenerator {
private static final int WIDTH = 120;
private static final int HEIGHT = 40;
private static final String CHARACTERS = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
private static final int CHARACTERS_LENGTH = CHARACTERS.length();
public static String generateCaptcha() {
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
Random random = new Random();
// Set background color
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, WIDTH, HEIGHT);
// Draw random characters
StringBuilder captcha = new StringBuilder();
for (int i = 0; i < 6; i++) {
char ch = CHARACTERS.charAt(random.nextInt(CHARACTERS_LENGTH));
captcha.append(ch);
int x = 10 + (i * 18);
int y = 18 + random.nextInt(10);
graphics.setColor(new Color(random.nextInt(200), random.nextInt(200), random.nextInt(200)));
graphics.setFont(new Font("Arial", Font.BOLD, 20));
graphics.drawString(Character.toString(ch), x, y);
}
// Draw random lines
for (int i = 0; i < 5; i++) {
int x1 = random.nextInt(WIDTH);
int y1 = random.nextInt(HEIGHT);
int x2 = random.nextInt(WIDTH);
int y2 = random.nextInt(HEIGHT);
graphics.setColor(new Color(random.nextInt(200), random.nextInt(200), random.nextInt(200)));
graphics.drawLine(x1, y1, x2, y2);
}
return captcha.toString();
}
}
```
以上就是生成验证码的Java代码案例。如果你对这个问题有更多疑问或者需要帮助,请随时告诉我。
阅读全文