Generate QR code using Hutool toolkit

Table of contents

use

Generate QR code

Custom parameters

1.Basic parameter settings

2. Comes with a small logo icon

3. Adjust the error correction level

Recognize QR code


use

Introduce Hutool toolkit dependencies:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.23</version>
</dependency>

Considering the non-mandatory dependency of Hutool, zxing needs to be introduced by the user:

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.3</version>
</dependency>

Generate QR code

For example, generate the URL of your personal blog homepage into a QR code, and scan it on WeChat to see the H5 homepage:

// 生成指定url对应的二维码到文件,宽和高都是300像素
QrCodeUtil.generate("https://blog.csdn.net/qq_74312711?spm=1000.2115.3001.5343", 300, 300, FileUtil.file("D:\\develop\\[a04]\\qrcode.jpg"));

Effect qrcode.jpg:

Custom parameters

1.Basic parameter settings

Through QrConfig, you can customize the QR code generation parameters, such as length, width, QR code color, background color, margins and other parameters. The usage method is as follows:

QrConfig config = new QrConfig(300, 300);
// 设置边距,既二维码和背景之间的边距
config.setMargin(3);
// 设置前景色,既二维码颜色(青色)
config.setForeColor(Color.CYAN.getRGB());
// 设置背景色(灰色)
config.setBackColor(Color.GRAY.getRGB());

// 生成二维码到文件,也可以到流
QrCodeUtil.generate("https://blog.csdn.net/qq_74312711?spm=1000.2115.3001.5343", config, FileUtil.file("D:\\develop\\[a04]\\qrcode.jpg"));

Effect qrcode.jpg:

2. Comes with a small logo icon

QrCodeUtil.generate(//
        "https://blog.csdn.net/qq_74312711?spm=1000.2115.3001.5343", //二维码内容
        QrConfig.create().setImg("D:\\develop\\[a04]\\logo.jpg"), //附带logo
        FileUtil.file("D:\\develop\\[a04]\\qrcode.jpg")//写出到的文件
);

The effect is as shown in the figure:

3. Adjust the error correction level

Many times, the QR code cannot be recognized, and then the error correction level needs to be adjusted. The error correction level is encapsulated using zxing's ErrorCorrectionLevel enumeration, including: L, M, Q, H, several parameters, from low to high. Low-level pixel blocks are larger and can be recognized from a distance, but occlusion will cause unrecognizability. The high level is the opposite. The pixel blocks are small, allowing a certain range of occlusion, but the pixel blocks are denser.

QrConfig config = new QrConfig();
// 高纠错级别
config.setErrorCorrection(ErrorCorrectionLevel.H);
QrCodeUtil.generate("https://blog.csdn.net/qq_74312711?spm=1000.2115.3001.5343", config, FileUtil.file("D:\\develop\\[a04]\\qrcode.jpg"));

The effect is as shown in the figure:

Recognize QR code

// decode -> "https://blog.csdn.net/qq_74312711?spm=1000.2115.3001.5343"
String decode = QrCodeUtil.decode(FileUtil.file("D:\\develop\\[a04]\\qrcode.jpg"));

Guess you like

Origin blog.csdn.net/qq_74312711/article/details/134885930