2023年9月15日 天气:晴

发布时间 2023-09-15 23:45:20作者: chrisrmas、

  今天学会了如何生成图片,然后在图片上生成随机数。

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.util.Random;

public class Main2 {
public static void main(String[] args) throws Exception{
// 1.画什么
String str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random random = new Random();
// 存生成的字母
String randomStr = "";
for (int i = 0; i < 4; ++ i)
{
// 拿一个数据的位置
int index = random.nextInt(str.length());
char letter = str.charAt(index);
randomStr += letter;
}

// 2.确定颜色
// 背景色:底色(0~255)
int red = random.nextInt(256);
int green = random.nextInt(256);
int blue = random.nextInt(256);
Color bgColor = new Color(red, green, blue);
// System.out.println(red + " " + green + " " + blue);
// 前景色:人物,文字)
int red2 = 255 - bgColor.getRed();
int green2 = 255 - bgColor.getGreen();
int blue2 = 255 - bgColor.getBlue();
Color foreColor = new Color(red2, green2, blue2);

// 3.开始画画(二维码)
// 3.1准备画纸(大小)
BufferedImage bufferedImage = new BufferedImage(80, 30, BufferedImage.TYPE_INT_RGB);

// 3.2 准备画笔
Graphics graphics = bufferedImage.getGraphics();

// 3.3 画纸涂满底色
graphics.setColor(bgColor);
graphics.fillRect(0, 0, 80, 30);

// 3.4 画笔换成前景色
graphics.setColor(foreColor);
graphics.setFont(new Font("黑体", Font.BOLD, 26));
graphics.drawString(randomStr, 10, 28);

// 画50个噪点
for (int i = 0; i < 50; ++ i)
{
graphics.setColor(Color.white);
int x = random.nextInt(80);
int y = random.nextInt(30);
graphics.fillRect(x, y, 1, 1);
}

// 3.5 展示观众
FileOutputStream fileOutputStream = new FileOutputStream("src/main/resources/imgs/code.jpg");

// 变成文件
ImageIO.write(bufferedImage, "jpeg", fileOutputStream);

System.out.println("二维码生成成功");
}
}