QR Code 應用日益普及,PHP 開發者常需在專案中動態產生二維碼。本文介紹兩種主流方案:呼叫 Google Chart API(零依賴、即時生成)與使用 PHP QR Code 類庫(離線、可嵌入 Logo),並詳細說明帶 Logo 進階技巧。
Google 提供簡單的 GET 介面,無需安裝任何擴充套件:
<?php
function generateQRfromGoogle($chl, $widthHeight = '150', $EC_level = 'L', $margin = '0') {
$chl = urlencode($chl);
echo '<img src="https://chart.googleapis.com/chart?chs='
. $widthHeight . 'x' . $widthHeight
. '&cht=qr&chld=' . $EC_level . '|' . $margin
. '&chl=' . $chl . '" alt="QR code" width="' . $widthHeight
. '" height="' . $widthHeight . '" />';
}
// 使用範例
generateQRfromGoogle("https://www.example.com");
?>
官網:phpqrcode.sourceforge.net,需 PHP 啟用 GD2 擴充。
<?php
include 'phpqrcode.php';
QRcode::png('https://www.example.com'); // 直接輸出圖片至瀏覽器
?>
原理:先生成 QR Code 圖片,再用 GD 函數將 Logo 置中疊加。因 QR Code 具備錯誤修正能力,遮蓋中心區域仍可正常掃描。
<?php
include 'phpqrcode.php';
$value = 'https://www.example.com';
$errorCorrectionLevel = 'L';
$matrixPointSize = 6;
// 1. 產生暫存 QR Code 檔案
QRcode::png($value, 'qrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);
$logo = 'logo.png';
$qr = 'qrcode.png';
if (file_exists($logo)) {
$qrImg = imagecreatefromstring(file_get_contents($qr));
$logoImg = imagecreatefromstring(file_get_contents($logo));
$qrW = imagesx($qrImg);
$qrH = imagesy($qrImg);
$logoW = imagesx($logoImg);
$logoH = imagesy($logoImg);
// Logo 寬度設為 QR Code 1/5
$logoQrW = $qrW / 5;
$scale = $logoW / $logoQrW;
$logoQrH = $logoH / $scale;
$fromW = ($qrW - $logoQrW) / 2;
// 重新取樣疊加
imagecopyresampled(
$qrImg, $logoImg,
$fromW, $fromW, 0, 0,
$logoQrW, $logoQrH,
$logoW, $logoH
);
}
// 輸出最終圖片
imagepng($qrImg, 'final_qrcode.png');
echo '<img src="final_qrcode.png" alt="QR Code with Logo" />';
?>
| 等級 | 修正能力 | 適用場景 |
|---|---|---|
| L | 7% | 一般用途、網址較短 |
| M | 15% | 含 Logo、中等長度內容 |
| Q | 25% | 高可靠度需求 |
| H | 30% | 惡劣環境、大量資料 |
根據專案需求選擇適合方案,若需品牌化呈現,帶 Logo 方案能顯著提升辨識度與專業形象。