[亲妈版]SpringBoot生成二维码

前言:

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

正式开发步骤:

1、引入Maven依赖




    com.google.zxing
    core
    3.3.0



    com.google.zxing
    javase
    3.3.0

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、测试

生成成功,可以扫码测试哟
[亲妈版]SpringBoot生成二维码_第1张图片

你可能感兴趣的:([亲妈版]SpringBoot生成二维码)