QR Code(快速響應碼)廣泛應用於行銷、登入、支付等場景。本文提供三種生成方案:Google ZXing 純 Java 後端生成(無 Logo/帶 Logo)與jQuery.qrcode 前端生成,附完整程式碼與關鍵細節說明。
public static void main(String[] args) {
try {
String content = "https://example.com"; // 內容
String path = "E:/qrcode/"; // 輸出目錄
MultiFormatWriter writer = new MultiFormatWriter();
Map hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, 400, 400, hints);
File file = new File(path, "basic_qrcode.jpg");
MatrixToImageWriter.writeToPath(bitMatrix, "jpg", file.toPath()); // ZXing 3.3+ 建議用法
System.out.println("QR Code 生成完成:" + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
關鍵點:
MultiFormatWriter 支援多種條碼格式,這裡指定 QR_CODE。EncodeHintType.CHARACTER_SET 設定編碼,避免中文亂碼。MatrixToImageWriter.writeToPath(),舊版用 ImageIO.write() 搭配自行轉換 BufferedImage。完整工具類 QRCodeUtil 核心邏輯:
ErrorCorrectionLevel.H 允許 30% 損壞仍可掃描,留空間給 Logo。BitMatrix 黑白點填充像素。(qrSize - logoW)/2, (qrSize - logoH)/2。Graphics2D 繪製 Logo,並可選繪製圓角矩形邊框。// 使用範例
public static void main(String[] args) throws Exception {
String url = "https://example.com";
String logoPath = "d:/logo.png";
String destDir = "e:/qrcode/";
QRCodeUtil.encode(url, logoPath, destDir, true); // true = 自動壓縮 Logo
}
完整 QRCodeUtil 原始碼請見原文,包含 createImage、insertImage、多重 encode 過載、mkdirs、decode 解碼等方法。
適合純前端頁面、動態參數生成 QR Code。
<div id="qrcode"></div>
<script src="jquery.min.js"></script>
<script src="jquery.qrcode.min.js"></script>
<script>
$("#qrcode").qrcode({
render: "canvas", // 或 "table" (IE 相容)
width: 200,
height: 200,
text: "https://example.com",
foreground: "#000",
background: "#fff"
});
</script>
| 場景 | 推薦方案 | 注意事項 |
|---|---|---|
| 後端批次產生、需存檔/寄信/列印 | ZXing 方案二(帶 Logo) | 設定 ErrorCorrectionLevel.H;Logo 佔比勿超過 20-25% |
| 簡單連結、無品牌化需求 | ZXing 方案一 | 最輕量、效能最好 |
| 前端互動頁、使用者自訂內容即時預覽 | jQuery.qrcode | 搭配 canvas.toBlob 下載圖片 |
| 需解碼掃描結果 | ZXing QRCodeUtil.decode() | 支援 File/路徑輸入 |
常見坑:
CHARACTER_SET = UTF-8,否則掃描出現亂碼。mkdirs(),避免 FileNotFoundException。