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

相关推荐
qq_5470261792 小时前
Flowable 工作流引擎
java·服务器·前端
鼓掌MVP3 小时前
Java框架的发展历程体现了软件工程思想的持续进化
java·spring·架构
编程爱好者熊浪3 小时前
两次连接池泄露的BUG
java·数据库
lllsure3 小时前
【Spring Cloud】Spring Cloud Config
java·spring·spring cloud
鬼火儿4 小时前
SpringBoot】Spring Boot 项目的打包配置
java·后端
NON-JUDGMENTAL4 小时前
Tomcat 新手避坑指南:环境配置 + 启动问题 + 乱码解决全流程
java·tomcat
cr7xin4 小时前
缓存三大问题及解决方案
redis·后端·缓存
大佬,救命!!!5 小时前
C++多线程同步与互斥
开发语言·c++·学习笔记·多线程·互斥锁·同步与互斥·死锁和避免策略
摇滚侠5 小时前
Spring Boot3零基础教程,Spring Boot 应用打包成 exe 可执行文件,笔记91 笔记92 笔记93
linux·spring boot·笔记
chxii5 小时前
Maven 详解(上)
java·maven