直接用java代码就可以生成随机验证码图片,具体流程如下:
1创建一张空白图片,同时指定宽高 理解为:搞一张白纸,准备画画
2通过图片获取绘制该图片的画笔,通过这个画笔就可以往该图片上绘制了
3随机生成个颜色涂满整张画布
4向画布上绘制文字
5随机生成若干条干扰线,也可以自己制定
public static void main(String[] args) {
//创建空白图片,用RGB来指定颜色
BufferedImage image = new BufferedImage(
70,30,BufferedImage.TYPE_INT_RGB
);
//获取画笔
Graphics pencil = image.getGraphics();
Random random = new Random();
//随机生成个颜色涂满整张画布
Color color = new Color(
random.nextInt(256),
random.nextInt(256),
random.nextInt(256));
pencil.setColor(color);//设置画笔颜色
pencil.fillRect(0,0,70,30);
//向画布上绘制文字,首先指定随机字符选取的范围
String line = "abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
pencil.setFont(new Font(null,Font.BOLD,20));
for(int i=0;i<4;i++) {
color = new Color(
random.nextInt(256),
random.nextInt(256),
random.nextInt(256));
pencil.setColor(color);//设置画笔颜色
String str = line.charAt(random.nextInt(line.length())) + "";
pencil.drawString(str, i*15+5, 18+ random.nextInt(11)-5);
}
//随机生成3条干扰线
for(int i=0;i<3;i++){
color = new Color(
random.nextInt(256),
random.nextInt(256),
random.nextInt(256));
pencil.setColor(color);//设置画笔颜色
pencil.drawLine(random.nextInt(71), random.nextInt(31),
random.nextInt(71), random.nextInt(31));
}
//设置图片后缀,并通过输出流输出
try {
ImageIO.write(image,"jpg",
new FileOutputStream("./random.jpg"));
System.out.println("图片已生成");
} catch (IOException e) {
e.printStackTrace();
}
}