Java 制作二维码
最近刷题遇到了java制作二维码的功能
pom文件
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
Java代码
public static void main(String[] args) {
String binaryString = "111111101010001111111\n" +
"100000100111001000001\n" +
"101110100010001011101\n" +
"101110100111101011101\n" +
"101110100100101011101\n" +
"100000100011001000001\n" +
"111111101010101111111\n" +
"000000001001000000000\n" +
"110110100111101000001\n" +
"010001010111011011110\n" +
"100100101010000000010\n" +
"100101001110101100000\n" +
"111101101010111010111\n" +
"000000001111001111111\n" +
"111111100000111001000\n" +
"100000100001001111100\n" +
"101110101010111000100\n" +
"101110101110010110110\n" +
"101110100111010100011\n" +
"100000101010000010100\n" +
"111111101101111010100";
// 去除换行符并分割成二维数组
String[] lines = binaryString.split("\n");
int width = lines[0].length();
int height = lines.length;
// 创建BufferedImage
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 填充图像
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
char c = lines[y].charAt(x);
if (c == '1') {
image.setRGB(x, y, Color.BLACK.getRGB());
} else if (c == '0') {
image.setRGB(x, y, Color.WHITE.getRGB());
}
}
}
// 保存图像
try {
File output = new File("C:\\Users\\Administrator\\Desktop\\QRCode.png");
ImageIO.write(image, "png", output);
System.out.println("图像已生成并保存为 binary_image.png");
} catch (IOException e) {
e.printStackTrace();
}
}