写一个图片验证算数形式的Java类
时间: 2023-08-15 14:03:08 浏览: 166
以下是一个简单的Java类,用于生成带有算术表达式的图片验证:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
public class ArithmeticCaptcha {
private static final int WIDTH = 120; // 图片宽度
private static final int HEIGHT = 40; // 图片高度
private static final int FONT_SIZE = 20; // 字体大小
private static final int STR_LENGTH = 4; // 验证码长度
private static final int MAX_NUM = 10; // 随机数最大值
public static BufferedImage createImage() {
// 创建图片缓冲区
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();
int num1 = random.nextInt(MAX_NUM);
int num2 = random.nextInt(MAX_NUM);
int operatorIndex = random.nextInt(2);
char operator = operatorIndex == 0 ? '+' : '-';
// 计算结果
int result = operatorIndex == 0 ? num1 + num2 : num1 - num2;
// 将算式绘制到图片上
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.BOLD, FONT_SIZE));
String expression = num1 + " " + operator + " " + num2 + " = ?";
g.drawString(expression, 10, 25);
// 绘制干扰线
int lineCount = 5;
for (int i = 0; i < lineCount; i++) {
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;
}
}
```
使用方法:
```java
// 生成图片验证码
BufferedImage image = ArithmeticCaptcha.createImage();
// 将图片验证码输出到文件或响应流
ImageIO.write(image, "JPEG", new File("captcha.jpg"));
```
阅读全文