研究一下二维码的生成吧!

1. 新建spring boot项目

1.1 pom.xml

<!-- 生成二维码依赖 -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.4.1</version>
</dependency>

1.2 新建生成二维码工具类

/**
 * 生成二维码工具类
 *
 * @author zhouzhaodong
 */
public class QRCodeGenerator {

    /**
     * 生成二维码图片
     * @param text
     * @param width
     * @param height
     * @param filePath
     * @throws WriterException
     * @throws IOException
     */
    public static void generateQRCodeImage(String text, int width, int height, String filePath)
            throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        Path path = FileSystems.getDefault().getPath(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
    }

    /**
     * 生成二维码流
     * @param text
     * @param width
     * @param height
     * @return
     */
    public static String writeToStream(String text, int width, int height) {
        String message = "";
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix;
        try {
            bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
            Base64.Encoder encoder = Base64.getEncoder();
            message = encoder.encodeToString(outputStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }

}

1.3 新建controller

/**
 * 生成二维码
 * @author zhouzhaodong
 */
@RestController
public class QRCodeController {

    /**
     * 生成二维码图片并将地址回传给前端
     * @param orderNo
     * @return
     */
    @RequestMapping("/qrcode/image")
    public String qrcodeImage(String orderNo) {
        String failPath = "src/main/resources/png/" + orderNo + ".png";
        try {
            QRCodeGenerator.generateQRCodeImage(orderNo, 350, 350,  failPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return failPath;
    }

    /**
     * 生成二维码Base64回传给前端
     * @param orderNo
     * @return
     */
    @RequestMapping("/qrcode/base64")
    public String qrcodeBase64(String orderNo) {
        String message = "";
        try {
            message = QRCodeGenerator.writeToStream(orderNo, 350, 350);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }

}

1.4 测试

这里我使用IDEA自带的HTTP请求客户端进行测试。

1.4.1 先测试生成图片的请求

image.png

image.png

1.4.2 再测试生成Base64的请求

image.png

可以去https://tool.jisuapi.com/base642pic.html去将Base64转为图片
image.png

源代码地址:

https://github.com/zhouzhaodong/springboot/tree/master/spring-boot-qrcode

上一篇 下一篇