PHP QR Code 是純 PHP 實作的 QR Code 產生器,無需安裝額外擴展,支援誤碼糾正等級、尺寸調整、直接輸出圖片或存檔。本文示範基本用法、檔案輸出、以及進階「二維碼中心嵌入 Logo」完整流程。
composer require chillerlan/php-qrcode (現代分支)。phpqrcode.php(舊版單檔)或自動載入。<?php
include 'phpqrcode/phpqrcode.php';
$value = 'https://www.example.com';
$errorCorrectionLevel = 'L'; // L/M/Q/H,L 最低容錯 7%
$matrixPointSize = 4; // 1-10,模組大小
QRcode::png($value, false, $errorCorrectionLevel, $matrixPointSize);
exit;
?>
<?php
include 'phpqrcode/phpqrcode.php';
$data = 'https://www.example.com';
$filename = 'qrcode.png';
$errorCorrectionLevel = 'L';
$matrixPointSize = 4;
$margin = 2; // 靜區邊距
QRcode::png($data, $filename, $errorCorrectionLevel, $matrixPointSize, $margin);
echo "Generated: $filename";
?>
原理:先生成高容錯(H 級)二維碼,再用 GD 將 Logo 縮放至二維碼寬度 1/5~1/4,置中覆蓋。高容錯確保遮蓋後仍可掃描。
<?php
include 'phpqrcode/phpqrcode.php';
$value = 'https://www.example.com';
$logoFile = 'logo.png'; // 建議透明背景 PNG
$qrFile = 'qrcode_raw.png';
$outputFile = 'qrcode_with_logo.png';
// 1. 產生高容錯二維碼(H 級,尺寸較大)
QRcode::png($value, $qrFile, 'H', 10, 2);
// 2. 載入圖片資源
$qr = imagecreatefromstring(file_get_contents($qrFile));
$logo = imagecreatefromstring(file_get_contents($logoFile));
if (!$qr || !$logo) {
die('圖片載入失敗');
}
// 3. 計算 Logo 目標尺寸(二維碼寬度 1/5)
$qrW = imagesx($qr);
$qrH = imagesy($qr);
$logoW = imagesx($logo);
$logoH = imagesy($logo);
$targetW = $qrW / 5;
$scale = $logoW / $targetW;
$targetH = $logoH / $scale;
// 4. 計算置中座標
$fromX = ($qrW - $targetW) / 2;
$fromY = ($qrH - $targetH) / 2;
// 5. 重採樣覆蓋(保持透明度)
imagecopyresampled($qr, $logo, $fromX, $fromY, 0, 0, $targetW, $targetH, $logoW, $logoH);
// 6. 輸出最終圖
imagepng($qr, $outputFile);
imagedestroy($qr);
imagedestroy($logo);
echo "<img src='$outputFile' alt='QR with Logo'>";
?>
| 參數 | 說明 | 建議值 |
|---|---|---|
| errorCorrectionLevel | 誤碼糾正等級:L(7%) M(15%) Q(25%) H(30%) | 嵌入 Logo 必須用 H |
| matrixPointSize | 單模組像素大小 | 4-10,Logo 版建議 ≥8 |
| margin | 靜區寬度(模組數) | 2-4 |
| Logo 尺寸比例 | 佔二維碼寬度比例 | 1/5 (20%) 較安全,不可超過 1/3 |
imagecolortransparent)。chillerlan/php-qrcode (Composer) 支援 PHP 8、更豐富輸出格式(SVG、EPS)、更好型別提示。