SpringBoot (批量)生成二维码工具类多种方法示例

一、引入依赖

XML 复制代码
 <dependency>
	<groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
	<version>3.4.1</version>
</dependency>

<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>core</artifactId>
	<version>3.4.1</version>
</dependency>

二、按照字符串生成二维码

java 复制代码
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class QRCodeGeneratorByString {

    public static void main(String[] args) {
        String filePath = "D:\\QRcode/qrcode";
        int width = 300;
        int height = 300;

        try {
            Map<EncodeHintType, Object> hintMap = new HashMap<>();
            hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hintMap.put(EncodeHintType.MARGIN, 1);
            hintMap.put(EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.L);

            // 设置背景色和前景色
            Color backgroundColor = Color.WHITE;
            Color foregroundColor = Color.BLACK;

            for (int i = 10; i <= 19; i++) {
                // 生成类似 Fboard001 的字符串
                String content = "Fboard" + String.format("%03d", i);
                String fileFullPath = filePath + i + ".png";

                BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hintMap);

                BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

                for (int x = 0; x < width; x++) {
                    for (int y = 0; y < height; y++) {
                        int color = matrix.get(x, y) ? foregroundColor.getRGB() : backgroundColor.getRGB();
                        image.setRGB(x, y, color);
                    }
                }

                File qrCodeFile = new File(fileFullPath);
                ImageIO.write(image, "png", qrCodeFile);

                System.out.println("QR Code for " + content + " generated successfully!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

三、按照Json文件生成二维码

方法一(将json字符串直接传入)

java 复制代码
public class QRCodeGeneratorByOne {

    public static void main(String[] args) {
        String json = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
        String filePath = "D:\\QRcode/qrcode.png";
        int width = 300;
        int height = 300;

        try {

            Map<EncodeHintType, Object> hintMap = new HashMap<>();
            hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hintMap.put(EncodeHintType.MARGIN, 1);
            hintMap.put(EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.L);

            // 设置背景色和前景色
            Color backgroundColor = Color.WHITE;
            Color foregroundColor = Color.BLACK;

            BitMatrix matrix = new MultiFormatWriter().encode(json, BarcodeFormat.QR_CODE, width, height, hintMap);

            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    int color = matrix.get(x, y) ? foregroundColor.getRGB() : backgroundColor.getRGB();
                    image.setRGB(x, y, color);
                }
            }

            File qrCodeFile = new File(filePath);
            ImageIO.write(image, "png", qrCodeFile);

            System.out.println("QR Code generated successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

方法二(将json文件导入方法)

如果,希望二维码中包含更多的信息,使用字符串已经无法满足的情况下,可以尝试使用json文件先根据 json文件,创建对应的对象:

java 复制代码
@Data
@Getter
@Setter
public class JsonData {
    private String name;
    private int age;
    private String city;
}

java 复制代码
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class QRCodeGenerator {
    public static void main(String[] args) {

        String jsonFilePath = "D:\\QRcode/file.json";
        generateQRCodeFromJsonFile(jsonFilePath);
    }
    public static void generateQRCodeFromJsonFile(String jsonFilePath) {
        try {
            // 读取JSON文件
            File file = new File(jsonFilePath);
            ObjectMapper objectMapper = new ObjectMapper();
            JsonData[] jsonDataArray = objectMapper.readValue(file, JsonData[].class);
            // 逐个解析JSON并生成二维码
            for (JsonData jsonData : jsonDataArray) {
                String jsonString = objectMapper.writeValueAsString(jsonData);
                // 生成二维码图片
                String qrCodeImagePath = generateQRCodeImage(jsonString);
                System.out.println("Generated QR Code for JSON: " + jsonString);
                System.out.println("QR Code image path: " + qrCodeImagePath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String generateQRCodeImage(String data) {
        int width = 300;
        int height = 300;
        String format = "png";
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        //加上三位随机数
        Random random = new Random();
        int end3 = random.nextInt(999);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height, hints);
            File qrCodeFile = new File("D:\\QRcode/qrcode"+end3+".png");
            MatrixToImageWriter.writeToFile(bitMatrix, format, qrCodeFile);
            return qrCodeFile.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

注意:

此处要求的文件格式是json数组,而不是json对象

相关推荐
秋难降15 分钟前
代码界的 “建筑师”:建造者模式,让复杂对象构建井然有序
java·后端·设计模式
孤雪心殇20 分钟前
如何安全,高效,优雅的提升linux的glibc版本
linux·后端·golang·glibc
bdgtd8817827 分钟前
动态修补C扩展模块的函数指针有哪些风险?安全的修补方案是什么?
c语言·开发语言·安全
jeffery89239 分钟前
4056:【GESP2403八级】接竹竿
数据结构·c++·算法
luquinn42 分钟前
实现统一门户登录跳转免登录
开发语言·前端·javascript
Forward♞44 分钟前
Qt——界面美化 QSS
开发语言·c++·qt
BillKu1 小时前
Spring Boot 多环境配置
java·spring boot·后端
new_daimond1 小时前
Spring Boot项目集成日志系统使用完整指南
spring boot·后端
哈基米喜欢哈哈哈2 小时前
Kafka复制机制
笔记·分布式·后端·kafka
君不见,青丝成雪2 小时前
SpringBoot项目占用内存优化
java·spring boot·后端