基於 PHP QRCode 函式庫擴展,實現超越黑白方塊的品牌化二維碼:自定義前景/背景色、三個定位角點顏色、嵌入 Logo、疊加背景圖片、多種輸出格式。本文詳細說明擴展參數與實戰技巧。
QRcode::IMGout(
string $text, // 編碼內容
mixed $outfile = false, // false=直接輸出, 路徑字串=儲存檔案, resource=寫入資源
int $level = QR_ECLEVEL_L, // 容錯率 L(7%) M(15%) Q(25%) H(30%)
int $size = 3, // 模組像素大小
array $col = [ // 顏色配置 RGB 陣列
[255,255,255], // [0] 背景色
[0,0,0], // [1] 左上角定位點外框
[0,0,0], // [2] 右上角定位點外框
[0,0,0], // [3] 左下角定位點外框
[0,0,0], // [4] 左上角定位點中心
[0,0,0], // [5] 右上角定位點中心
[0,0,0], // [6] 左下角定位點中心
[0,0,0], // [7] 數據區顏色
false // [8] 數據區漸層 (保留)
],
int $margin = 2, // 靜區寬度 (模組數)
bool $saveandprint = false, // 儲存檔案時是否同時輸出
mixed $logo = false, // Logo 圖片路徑或 GD 資源
mixed $bg = false, // 背景圖配置陣列
string $type = 'png' // 輸出格式 png/gif/jpg
);
$bg = [
'logo_path.png', // [0] Logo 圖片路徑
0, // [1] 背景寬度 (0=自動)
0, // [2] 背景高度 (0=保持比例)
0.3, // [3] Logo 佔背景較短邊比例 (0.3=30%)
0, // [4] Logo X 偏移 (0=置中)
0 // [5] Logo Y 偏移 (0=置中)
];
※ Logo 會自動裁剪為正方形、添加白邊、圓角透明處理 (需 GD 支援)。
require 'phpqrcode.php';
$config = [
'text' => 'https://example.com/product/12345?utm_source=qrcode',
'level' => QR_ECLEVEL_H, // 高容錯,利於 Logo 遮蓋
'size' => 6, // 較大模組,掃描更易
'col' => [
[255, 255, 255], // 白底
[0, 51, 102], // 定位點外框:深藍
[0, 51, 102],
[0, 51, 102],
[0, 102, 204], // 定位點中心:亮藍
[0, 102, 204],
[0, 102, 204],
[0, 51, 102] // 數據區:深藍
],
'margin' => 3,
'logo' => 'assets/logo.png',
'bg' => [
'assets/bg_pattern.png', // 輕紋理背景
0, 0, 0.25, 0, 0
],
'type' => 'png'
];
QRcode::IMGout(
$config['text'], false, $config['level'], $config['size'],
$config['col'], $config['margin'], false, $config['logo'],
$config['bg'], $config['type']
);
| 因素 | 建議 | 原因 |
|---|---|---|
| 容錯等級 | H (30%) | Logo 遮蓋約 20-30% 區域,需高容錯 |
| 模組大小 | ≥ 4px | 太小導致列印/螢幕解析度不足無法識別 |
| 對比度 | 前景/背景 ≥ 4.5:1 | WCAG AA 標準,確保各環境可讀 |
| 靜區 | ≥ 4 模組 | 防止邊緣干擾圖案影響定位 |
| Logo 尺寸 | ≤ 30% 短邊 | 過大破壞定位點或數據區 |
function generate_qr_cached($url, $options = []) {
$hash = md5($url . serialize($options));
$cache_file = "cache/qr_{$hash}.png";
if (file_exists($cache_file) && (time() - filemtime($cache_file) < 86400*30)) {
return $cache_file; // 30天快取
}
QRcode::IMGout($url, $cache_file, ...$options);
return $cache_file;
}
本站提供即時生成工具:jb51 QRCode Generator,支援即時預覽參數效果。
掌握這些進階技巧,即可為行銷活動、產品包裝、會員卡片生成兼具品牌辨識度與高掃描率的專業二維碼。