Bootstrap

使用java生成二维码和二维码的解析

在Java中生成二维码可以使用第三方库,如Google的Zxing。

1、引入依赖

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

2、编写测试类 

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;

public class QRCodeGenerator {
    private static final int QR_CODE_SIZE = 200;

    public static void main(String[] args) throws WriterException, IOException {
        String text = "Hello, World!";
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE);
        Path path = FileSystems.getDefault().getPath("qrcode.png");
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
        System.out.println("二维码已生成:" + path);
    }
}

这段代码会生成一个包含文本 "Hello, World!" 的二维码,并将其保存为当前目录下的 "qrcode.png" 文件。可以修改 text 变量来设置不同的内容。

3、二维码解析

import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class QRCodeReader {
    public static void main(String[] args) {
        try {
            File qrCodeImage = new File("qrcode.png"); // 替换为你的二维码图片路径
            BufferedImage bufferedImage = ImageIO.read(qrCodeImage);
            LuminanceSource luminanceSource = new BufferedImageLuminanceSource(bufferedImage);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));

            Result result = new MultiFormatReader().decode(binaryBitmap);
            String text = result.getText();

            System.out.println("解析到的二维码内容: " + text);
        } catch (NotFoundException e) {
            System.out.println("未找到二维码或二维码内容无法解析");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("读取二维码图片时发生错误");
            e.printStackTrace();
        }
    }
}

 

;