Pu Zhibing
2025-02-28 8baab7959e8efd5be4c0276b7759c2b677eeb7df
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.ruoyi.common.core.utils.uuid;
 
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
 
public class QRCodeGenerator {
 
    /**
     * 生成二维码图片的base64编码
     * @param text
     * @param width
     * @param height
     * @return
     * @throws WriterException
     * @throws IOException
     */
    public static String generateQRCodeBase64(String text, int width, int height) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
 
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
        byte[] pngData = pngOutputStream.toByteArray();
 
        return Base64.getEncoder().encodeToString(pngData);
    }
 
    public static void main(String[] args) {
        try {
            String text = "Hello, World!";
            String base64QRCode = generateQRCodeBase64(text, 200, 200);
            System.out.println("Base64 QR Code: " + base64QRCode);
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }
    }
}