//验证码测试
//1创建一张空图片,并且指定宽高。 理解为:创建一张画纸
BufferedImage image = new BufferedImage(70,30,BufferedImage.TYPE_INT_RGB);
//2根据图片获取一个画笔,通过该画笔画的内容都会画到该图片上
Graphics g = image.getGraphics();
//3确定验证码内容(字母与数字的组合)
String line = "abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();//用于生成随机数(随机数位line的字符下标)
//为图片背景填充一个随机颜色
//创建Color时,需要指定三个参数,分别是,红,绿,蓝。数字范围都是(0-255)之间
Color bgcolor = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
//将画笔设置为该颜色
g.setColor(bgcolor);
//填充整张图片为画笔当前颜色
g.fillRect(0,0,70,30);
//向图片上画4个字符
for(int i=0;i<4;i++) {
//随机生成一个字符
String str = line.charAt(random.nextInt(line.length())) + "";
//生成随机颜色
Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
//设置画笔颜色
g.setColor(color);
//设置字体
g.setFont(new Font(null, Font.BOLD, 20));
//将字符串画到图片指定的位置上
g.drawString(str, i*15+5, 18+ random.nextInt(11)-5);
}
//随机生成4条干扰线
for (int i=0;i<4;i++){
Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
g.setColor(color);
g.drawLine(random.nextInt(71), random.nextInt(31),
random.nextInt(71), random.nextInt(31));
}
//将图片写入文件来生成该图片文件
try {
ImageIO.write(image,"jpg",new FileOutputStream("./random.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
java代码,实现验证码制作
于 2022-04-22 19:13:01 首次发布