在 Java 中生成二维码需要使用第三方库,常用的有 ZXing 和 QRCode 两个库,其中 ZXing 功能比较全面,支持多种码的生成和识别,QRCode 则只支持 QR 码的生成。

下面以 ZXing 库为例,演示在 Java 中如何生成二维码。

  1. 引入依赖

在项目的 pom.xml 文件中添加以下依赖:

<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>
  1. 生成二维码
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class QRCodeGenerator {

    public static void main(String[] args) {
        String text = 'https://www.example.com'; // 二维码的内容
        int width = 300; // 二维码的宽度
        int height = 300; // 二维码的高度
        String format = 'png'; // 二维码的格式

        // 定义二维码的参数
        java.util.Map<EncodeHintType, Object> hints = new java.util.HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, 'utf-8'); // 指定字符编码为utf-8
        hints.put(EncodeHintType.MARGIN, 1); // 设置二维码边缘空白大小为1

        try {
            // 生成二维码
            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix matrix = writer.encode(text, BarcodeFormat.QR_CODE, width, height, hints);

            // 创建BufferedImage对象
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            image.createGraphics();
            Graphics2D graphics = (Graphics2D) image.getGraphics();
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, width, height);
            graphics.setColor(Color.BLACK);

            // 将二维码画到BufferedImage对象中
            for (int i = 0; i < width; i++) {
                for (int j = 0; j < height; j++) {
                    if (matrix.get(i, j)) {
                        graphics.fillRect(i, j, 1, 1);
                    }
                }
            }

            // 保存二维码图片
            File file = new File('QRCode.png');
            ImageIO.write(image, format, file);

            System.out.println('二维码生成成功!');

        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上面的代码中,首先定义了二维码的内容、宽度、高度和格式等参数。然后通过 ZXing 库的 QRCodeWriter 类生成一个 BitMatrix 对象,表示二维码的矩阵。接着创建一个 BufferedImage 对象,并将二维码画到这个对象中。最后将图片保存为文件。

运行程序后,会在项目的根目录下生成一个名为 QRCode.png 的二维码图片。

以上就是使用 Java 生成二维码的方法。如果想要生成其他类型的码,可以参考 ZXing 库的官方文档。

Java 生成二维码教程 - 使用 ZXing 库

原文地址: https://www.cveoy.top/t/topic/l5jX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录