代码实现:
public class Main {
/**
* 验证码字符个数
*/
private static final int CHAR_NUM = 4;
/**
* 遮挡线条数
*/
private static final int LINE_NUM = 15;
public static void main(String[] args) {
createImage();
}
private static void createImage() {
try {
// 定义图片宽高
int width = 100;
int height = 50;
// 在内存中创建图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 绘制背景和边框
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
// 创建随机字符集和随机数对象
String str = "ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
Random random = new Random();
for (int i = 0; i < CHAR_NUM; i++) {
// 获取随机字符
int index = random.nextInt(str.length());
char ch = str.charAt(index);
// 获取随机颜色
Color randomColor = getRandomColor(random);
g.setColor(randomColor);
// 设置字体
Font font = new Font("微软雅黑", Font.BOLD, height / 2);
g.setFont(font);
// 写入验证码
g.drawString(ch + "", (i == 0) ? width / 4 * i + 2 : width / 4 * i, height - height / 4);
}
// 绘制干扰线
for (int i = 0; i < LINE_NUM; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
Color randomColor = getRandomColor(random);
g.setColor(randomColor);
g.drawLine(x1, y1, x2, y2);
}
File file = new File("image.jpg");
FileOutputStream out = new FileOutputStream(file);
// 写入文件
ImageIO.write(image, "jpg", out);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 随机颜色生成方法
*
* @param random 随机对象
* @return 随机颜色
*/
private static Color getRandomColor(Random random) {
int colorIndex = random.nextInt(3);
switch (colorIndex) {
case 1:
return Color.BLUE;
case 2:
return Color.GREEN;
case 3:
return Color.RED;
default:
return Color.MAGENTA;
}
}
}
生成结果:
![](https://img.haomeiwen.com/i19755741/0fa2b40ca25f9b6c.jpg)
网友评论