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对象

相关推荐
有梦想的骇客5 小时前
书籍“之“字形打印矩阵(8)0609
java·算法·矩阵
why1516 小时前
微服务商城-商品微服务
数据库·后端·golang
Chenyu_3106 小时前
12.找到字符串中所有字母异位词
c语言·数据结构·算法·哈希算法
yours_Gabriel6 小时前
【java面试】微服务篇
java·微服务·中间件·面试·kafka·rabbitmq
门前云梦7 小时前
《C语言·源初法典》---C语言基础(上)
c语言·开发语言·学习
hashiqimiya7 小时前
android studio中修改java逻辑对应配置的xml文件
xml·java·android studio
liuzhenghua668 小时前
Python任务调度模型
java·运维·python
結城8 小时前
mybatisX的使用,简化springboot的开发,不用再写entity、mapper以及service了!
java·spring boot·后端
小前端大牛马8 小时前
java教程笔记(十一)-泛型
java·笔记·python
Bruk.Liu8 小时前
《Minio 分片上传实现(基于Spring Boot)》
前端·spring boot·minio