Java生成二维码

创建二维码

依赖导入

xml 复制代码
    <dependency>
            <!--
                ZXing(Zebra Crossing)核心库,提供了二维码生成和解析的基本功能
            -->
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!--
            ZXing 的 JavaSE 扩展库,提供了在 Java 环境中生成和解析二维码的更高级功能,
            例如将二维码保存为图像文件、从图像文件解析二维码等。
        -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.4.1</version>
        </dependency>

工具类

java 复制代码
package com.sin.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @createTime 2023/10/17 10:07
 * @createAuthor SIN
 * @use 二维码创建工具类
 */
public class QRCodeUtil {


    private static final int WIDTH = 300; // 二维码宽度
    private static final int HEIGHT = 300; // 二维码高度
    private static final String FORMAT = "png"; // 二维码格式

    /**
     * 生成二维码
     * @param text 二维码内容,一定是互联网内容,本地是无法扫的到的
     * @param filePath 二维码生成地址
     */
    public static void generateQRCode(String text, String filePath) {
        try {
            
            // 创建一个存储编码参数的 HashMap 对象
            Map<EncodeHintType, Object> hints = new HashMap<>();
            // 设置字符集为 UTF-8
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            // 设置容错级别为 M
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            // 设置边距为 2
            hints.put(EncodeHintType.MARGIN, 2);

            // 使用 MultiFormatWriter 类将指定文本 text 编码为二维码矩阵
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);

            // 将二维码矩阵转换为 BufferedImage 对象
            BufferedImage image = toBufferedImage(bitMatrix);

            // 创建一个表示目标文件的 File 对象
            File file = new File(filePath);
            // 将 BufferedImage 对象保存为图像文件
            ImageIO.write(image, FORMAT, file);

            System.out.println("二维码已生成,保存路径:" + filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将二维码矩阵转为可视化图像
     * @param matrix
     * @return 生成BufferdImage对象,获得二维码的可视化图像
     */
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        // 获取二维码的宽和高
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        // 创建一个新的BufferedImage对象,指定宽和高,已经颜色类型
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                // 获取当前坐标 (x, y) 的像素值(true 表示黑色,false 表示白色)
                boolean pixel = matrix.get(x, y);
                // 根据像素值设置对应位置的 RGB 值,将黑色或白色像素点绘制到 BufferedImage 对象中
                int rgb = pixel ? Color.BLACK.getRGB() : Color.WHITE.getRGB();
                // 设置x,y坐标和颜色
                image.setRGB(x, y, rgb);
            }
        }
        // 返回生成的 BufferedImage 对象
        return image;
    }
}

测试

java 复制代码
package com.sin.test;

import com.sin.util.QRCodeUtil;

public class QRCodeExample {


    public static void main(String[] args) {
        String text = "https://trademark.zbjimg.com/pattern-prod/2017/image_52/27155581.jpg"; // 二维码中的文本内容
        String filePath = "D:/qrcode.png"; // 二维码保存路径

        QRCodeUtil.generateQRCode(text, filePath);
        System.out.println("生成成功");
    }
}

生成的二维码

相关推荐
考虑考虑1 小时前
Jpa使用union all
java·spring boot·后端
用户3721574261351 小时前
Java 实现 Excel 与 TXT 文本高效互转
java
浮游本尊2 小时前
Java学习第22天 - 云原生与容器化
java
渣哥4 小时前
原来 Java 里线程安全集合有这么多种
java
间彧4 小时前
Spring Boot集成Spring Security完整指南
java
间彧5 小时前
Spring Secutiy基本原理及工作流程
java
Java水解6 小时前
JAVA经典面试题附答案(持续更新版)
java·后端·面试
洛小豆8 小时前
在Java中,Integer.parseInt和Integer.valueOf有什么区别
java·后端·面试
前端小张同学8 小时前
服务器上如何搭建jenkins 服务CI/CD😎😎
java·后端
ytadpole8 小时前
Spring Cloud Gateway:一次不规范 URL 引发的路由转发404问题排查
java·后端