首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 二維碼/QR Code 生成庫選型指南:ZXing vs J4L vs Google Chart API

     編輯:Java 相關知識

主流開源庫對比

庫特點授權Maven 坐標推薦指數
ZXing (Zebra Crossing)功能最全,支援 QR Code、Data Matrix、Aztec、條碼等;同時支援編碼/解碼;Android 官方採用Apache 2.0com.google.zxing:core:3.5.1⭐⭐⭐⭐⭐
QRGenZXing 簡易封裝,API 極簡 (QRCode.from("text").to(ImageType.PNG).writeTo(path))Apache 2.0com.github.kenglxn.QRGen:javase:2.6.0⭐⭐⭐⭐
J4L-QRCode輕量、純 Java、無依賴,僅支援 QR Code 編碼,Jar 約 100KB商業/免費版官網下載 Jar 手動安裝⭐⭐⭐
Google Chart API (已停用)曾提供線上圖片生成,2019 年正式關閉,不可用於新專案免費N/A❌

ZXing 完整代碼範例

生成 QR Code (含 Logo)

public static void generateQR(String content, File output, String logoPath) throws Exception {
    Map<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 30% 容錯
    hints.put(EncodeHintType.MARGIN, 1);

    BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 300, 300, hints);
    
    // 加 Logo
    if (logoPath != null) {
        BufferedImage logo = ImageIO.read(new File(logoPath));
        int logoW = matrix.getWidth() / 5;
        int logoH = matrix.getHeight() / 5;
        int x = (matrix.getWidth() - logoW) / 2;
        int y = (matrix.getHeight() - logoH) / 2;
        // 將 matrix 轉 BufferedImage 再畫 logo
        BufferedImage qrImg = MatrixToImageWriter.toBufferedImage(matrix);
        Graphics2D g = qrImg.createGraphics();
        g.drawImage(logo, x, y, logoW, logoH, null);
        g.dispose();
        ImageIO.write(qrImg, "PNG", output);
    } else {
        MatrixToImageWriter.writeToPath(matrix, "PNG", output.toPath());
    }
}

解碼 QR Code

public static String decodeQR(File imageFile) throws Exception {
    BufferedImage img = ImageIO.read(imageFile);
    LuminanceSource source = new BufferedImageLuminanceSource(img);
    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
    Result result = new MultiFormatReader().decode(bitmap);
    return result.getText();
}

J4L-QRCode 簡易用法 (若專案極度在意 Jar 大小)

// 需手動將 qrcode.jar 加入 classpath
import com.java4less.qrcode.QRCode;

QRCode qr = new QRCode();
qr.setData("https://example.com");
qr.setErrorCorrection(QRCode.ERROR_CORRECTION_H);
qr.setModuleSize(4);
BufferedImage img = qr.getImage();
ImageIO.write(img, "PNG", new File("qrcode.png"));

選型建議

  • 通用專案:首選 ZXing,生態成熟、文檔豐富、同時解決生成與掃描。
  • Spring Boot 整合:可引入 com.github.axet:zxing:3.5.1 或自寫 QRCodeService 封裝。
  • 嵌入式/極簡環境:考慮 J4L-QRCode (純 Java、無依賴、Jar 小)。
  • 前端生成:後端只回傳字串,前端用 qrcode.js 或 vue-qrcode 渲染,減輕後端壓力。

QR Code 參數小知識

  • 版本:1~40,版本越高容量越大 (版本 1: 21x21 modules)。
  • 容錯等級:L (7%)、M (15%)、Q (25%)、H (30%)。帶 Logo 必須用 H。
  • 編碼模式:數字、字母數字、Byte (UTF-8)、漢字 (Shift_JIS)。中文建議用 UTF-8 Byte 模式。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved