二維碼生成工具類

entaro發表於2022-01-17

0、需先引入google的zxing包

<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.4.1</version>
</dependency>

1、傳入一個字串,生成一個二維碼檔案(存放在臨時資料夾中)

public File generateQrcodeFile(String content) {
        try {
            int width = 220;
            int height = 220;
            String format = "png";
            Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
            hints.put(EncodeHintType.MARGIN, 0);
            BitMatrix bm = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            Path qrcodePath = Paths.get(System.getProperty("java.io.tmpdir"), "二維碼_" + System.currentTimeMillis() + ".png");
            MatrixToImageWriter.writeToPath(bm, format, qrcodePath);
            return qrcodePath.toFile();
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

2、傳入一個字串和HttpServletResponse物件,直接將二維碼返回到流中

public void generateQrcodeResponse(String content, HttpServletResponse response) throws Exception {
        File file = this.generateQrcodeFile(content);
        InputStream inputStream = new FileInputStream(file);
        BufferedInputStream br = new BufferedInputStream(inputStream);
        byte[] buf = new byte[1024];
        int len;
        response.reset();
        response.setContentType("image/png");
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        br.close();
        out.close();
    }
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章