二維碼中心嵌入 Logo 是常見需求。利用 QR 碼的**容錯特性**(最高 30% 損壞可恢復),將 Logo 覆蓋在中心區域。本文提供完整 GD 實現代碼,涵蓋縮放計算、透明度保持、容錯等級選擇、輸出優化。
imagecopyresampled 高質量縮放,保持清晰度。<?php
/**
* 生成帶 Logo 的二維碼
* @param string $content 二維碼內容
* @param string $logoPath Logo 文件路徑 (PNG 透明背景)
* @param string $outputPath 輸出路徑,為空則直接輸出瀏覽器
* @param int $size 二維碼寬高 (像素)
* @param string $level 容錯級別 L/M/Q/H (必須用 H)
* @param int $margin 邊距
* @param float $logoRatio Logo 佔比 (0.15-0.2 建議 0.18)
*/
function generateQRWithLogo(
string $content,
string $logoPath,
string $outputPath = '',
int $size = 300,
string $level = 'H',
int $margin = 2,
float $logoRatio = 0.18
): bool {
// 1. 驗證 GD 和內容
if (!extension_loaded('gd')) {
trigger_error('GD extension required', E_USER_ERROR);
return false;
}
if (empty($content)) return false;
// 2. 生成基礎二維碼 (需安裝 php-qrcode 庫或使用 Google Chart API 替代)
// 這裡使用流行的 phpqrcode 庫: https://github.com/t0k4rt/phpqrcode
require_once 'phpqrcode/qrlib.php'; // 假設已引入
$tempQR = tempnam(sys_get_temp_dir(), 'qr_');
$errorCorrection = match($level) {
'L' => QR_ECLEVEL_L,
'M' => QR_ECLEVEL_M,
'Q' => QR_ECLEVEL_Q,
'H' => QR_ECLEVEL_H,
default => QR_ECLEVEL_H,
};
// 生成原始 QR 碼圖片
QRcode::png($content, $tempQR, $errorCorrection, $size / 37, $margin); // 37 是 QR 碼模塊數估算
// 3. 載入資源
$qr = imagecreatefromstring(file_get_contents($tempQR));
unlink($tempQR); // 刪除臨時文件
if (!$qr) return false;
// 4. 處理 Logo
if (is_file($logoPath)) {
$logo = imagecreatefromstring(file_get_contents($logoPath));
if ($logo) {
// 開啟 Alpha 混合
imagealphablending($qr, true);
imagesavealpha($qr, true);
$qrWidth = imagesx($qr);
$qrHeight = imagesy($qr);
$logoWidth = imagesx($logo);
$logoHeight = imagesy($logo);
// 計算 Logo 目標尺寸
$targetWidth = $qrWidth * $logoRatio;
$targetHeight = $logoWidth > 0 ? ($logoHeight * $targetWidth / $logoWidth) : $targetWidth;
// 限制最大不超過 QR 碼 1/3
$maxSize = $qrWidth / 3;
if ($targetWidth > $maxSize) {
$targetWidth = $maxSize;
$targetHeight = $logoHeight * $targetWidth / $logoWidth;
}
// 居中坐標
$dstX = ($qrWidth - $targetWidth) / 2;
$dstY = ($qrHeight - $targetHeight) / 2;
// 高質量重採樣複製
imagecopyresampled(
$qr, $logo,
$dstX, $dstY, 0, 0,
$targetWidth, $targetHeight,
$logoWidth, $logoHeight
);
imagedestroy($logo);
}
}
// 5. 輸出
if ($outputPath) {
$result = imagepng($qr, $outputPath);
} else {
header('Content-Type: image/png');
$result = imagepng($qr);
}
imagedestroy($qr);
return $result;
}
// ========== 使用示例 ==========
// 1. 直接輸出瀏覽器
generateQRWithLogo('https://example.com/user/123', __DIR__ . '/logo.png');
// 2. 保存文件
generateQRWithLogo(
'https://shop.example.com/product/456',
__DIR__ . '/logo.png',
__DIR__ . '/qrcode_product_456.png',
400, 'H', 2, 0.18
);
| 參數 | 推薦值 | 說明 |
|---|---|---|
| 容錯級別 | H (30%) | 嵌入 Logo 必須用最高級,否則掃碼失敗率極高 |
| Logo 佔比 | 0.15 ~ 0.20 (建議 0.18) | 太大超過容錯能力,太小視覺效果差 |
| 二維碼尺寸 | ≥ 300px | 太小導致 Logo 模糊、掃換困難;打印建議 500px+ |
| 邊距 | 2~4 模塊 | 留白區域,掃碼器識別邊界用 |
| Logo 格式 | PNG 透明背景 | JPG 無透明通道會有白框;SVG 需轉 PNG |
| Logo 內容 | 簡單圖標、首字母 | 複雜圖片縮小後不可辨識,建議用品牌首字母或簡約 Logo |
function googleQR(string $content, int $size = 300, string $level = 'H'): string
{
$params = http_build_query([
'chs' => "${size}x${size}",
'cht' => 'qr',
'chl' => $content,
'chld' => $level . '|2', // 級別|邊距
]);
return "https://chart.googleapis.com/chart?{$params}";
}
// 使用
echo '
';
// 注意:Google Chart API 已官方棄用,可能隨時停止服務,生產環境請用本地庫
// composer require endroid/qrcode
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\Writer\PngWriter;
$qrCode = new QrCode('https://example.com');
$qrCode->setSize(300);
$qrCode->setMargin(10);
$qrCode->setErrorCorrectionLevel('high'); // H 級
// 添加 Logo
$logo = new Logo(__DIR__ . '/logo.png');
$logo->setWidth(60); // 直接設置寬度,庫會自動計算比例
$qrCode->setLogo($logo);
// 可選:添加標簽
$label = new Label('掃碼關注', 16);
$qrCode->setLabel($label);
$writer = new PngWriter();
$result = $writer->write($qrCode);
// 保存
file_put_contents('qrcode.png', $result->getString());
// 或直接輸出
header('Content-Type: image/png');
echo $result->getString();
給二維碼加 Logo 核心在於:**選 H 級容錯 + 控制 Logo 面積 < 20% + 透明 PNG + 高質量縮放**。推薦使用成熟庫 endroid/qrcode,內置處理了所有細節(容錯計算、Logo 縮放、標簽、顏色自定義、多種輸出格式),避免手寫 GD 代碼踩坑。若項目極簡、不想引入依賴,上文原生 GD 代碼經過實測可直接用於生產環境。