java生成登录四位数字验证码带样式
时间: 2024-02-22 07:18:34 浏览: 18
你可以使用以下代码来生成一个带样式的四位数字验证码:
```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 int CODE_LENGTH = 4; // 验证码长度
public static BufferedImage generateCaptcha() {
// 创建一个图像对象
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 设置背景色为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
// 创建随机数生成器
Random random = new Random();
// 设置字体样式
Font font = new Font("Arial", Font.BOLD, 30);
g.setFont(font);
// 生成随机验证码
StringBuilder code = new StringBuilder();
for (int i = 0; i < CODE_LENGTH; i++) {
int digit = random.nextInt(10); // 生成0-9之间的随机数
code.append(digit);
}
// 绘制验证码
for (int i = 0; i < CODE_LENGTH; i++) {
int x = i * (WIDTH / CODE_LENGTH) + 10;
int y = HEIGHT / 2 + 10;
g.setColor(getRandomColor());
g.drawString(String.valueOf(code.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);
}
// 添加噪点
for (int i = 0; i < 50; i++) {
int x = random.nextInt(WIDTH);
int y = random.nextInt(HEIGHT);
int rgb = getRandomColor().getRGB();
image.setRGB(x, y, rgb);
}
// 完成绘制
g.dispose();
return image;
}
private static Color getRandomColor() {
Random random = new Random();
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
return new Color(r, g, b);
}
}
```
使用示例:
```java
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
BufferedImage captchaImage = CaptchaGenerator.generateCaptcha();
// 保存验证码图片到文件
try {
File outputfile = new File("captcha.jpg");
ImageIO.write(captchaImage, "jpg", outputfile);
System.out.println("验证码已保存到 " + outputfile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码将生成一个带样式的四位数字验证码,并将其保存为名为 "captcha.jpg" 的文件。你可以根据需要调整验证码的样式和保存位置。