关于springboot:亲妈版SpringBoot生成二维码

54次阅读

共计 1640 个字符,预计需要花费 5 分钟才能阅读完成。

前言:

本文基于 JAVA 环境,以 SpringBoot 框架为根底开发。

正式开发步骤:

1、引入 Maven 依赖

<!-- 引入生成二维码的依赖 -->
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.3.0</version>
</dependency>

2、创立生成二维码工具类 QRCodeGenerator.java

/**
 * Java 生成二维码
 * @date: 2022/6/16 21:21
 * @author: gxw
 */
public class QRCodeGenerator {
    // 生成的二维码的门路
    private static String QR_CODE_IMAGE_PATH = PropertiesValues.getPropertiesValue("wx.pay.img.generator_path", "application.properties");
    // 正式上线前缀
    private static String PAY_PREFIX = PropertiesValues.getPropertiesValue("wx.pay.img.prefix", "application.properties");
    // 二维码图片的宽度
    private static int WIDTH = 500;
    // 二维码图片的高度
    private static int HEIGHT = 500;

    public static String generateQRCodeImage(String content) throws Exception {QR_CODE_IMAGE_PATH = PropertiesValues.getPropertiesValue("wx.pay.img.generator_path", "application.properties");
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// H 最高容错等级
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

        BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT,hints);
        String imgName = RandomUtils.generateRandomString(6) + ".png";
        QR_CODE_IMAGE_PATH += imgName;
        File file = new File(QR_CODE_IMAGE_PATH);
        if(!file.exists()){file.mkdirs();
        }

        Path path = FileSystems.getDefault().getPath(QR_CODE_IMAGE_PATH);

        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

        return PAY_PREFIX + imgName;
    }
}

3、测试

生成胜利,能够扫码测试哟

正文完
 0