版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40990836/article/details/79100854
public class Code{
static List<Character> list = new ArrayList<>();
// 使用静态代码块,将随机的字母和数字添加到集合中
static{
char number = '0';
char smallLetter = 'a';
char bigLetter = 'A';
for(int i = 0; i < 26; i++){
if(i<10){
// 将0-9个字符添加到集合中
list.add(number++);
}
// 将小写字母添加到list 集合中
list.add(smallLetter++);
list.add(bigLetter++);
}
}
public static void main(String[] agrs){
// 获取验证码
String code = getCode();
// 表示一个具有八位RGB颜色的图像
BufferedImage image = new BufferedImage(70,28,BufferedImage.TYPE_INT_BRG);
// 获取image对象的画笔
Grahics gra = image.getGraphics();
// 设置背景颜色
gra.setColor(Color.BLACK);
// 绘制图形
gra.fillRect(0,0,70,25)
// 设置画笔的颜色
graphics.setColor(Color.red);
// 字体的属性
// 参数 Font.SERIF 逻辑字体 Font.TYPE1_FONT 字体资源
graphics.setFont(new Font(Font.SERIF, Font.TYPE1_FONT, 25));
// 将随机字符串画在图片上
graphics.drawString(code, 5, 20);
File file = new File("/Users/lanou/Desktop",code + ".png");
try {
ImageIO.write(image, "png", file);
System.out.println("图像写入成功" + file.getAbsolutePath());
} catch (IOException e) {
System.out.println("异常 : IOException" + e.getMessage());
}
}
public static String getCode(){
// 创建Random对象
Random random = new Random();
// 拼接字符串
StringBuffer sb = new StringBuffer();
for(int i = 0;i < 4; i++){
// 从list的长度大小的数字随机出来四个数字
int ranNum = random.nextInt(list.size());
Character char = list.get(ranNum);
sb.append(char);
}
return new String(sb);
}
}