利用 Google Chart API 快速生成二維碼,並疊加 Logo 圖標,適合名片、推廣海報等場景。
<?php
// 參數獲取
$data = $_GET['t'] ?? 'https://example.com';
$size = $_GET['size'] ?? '150x150';
$logoPath = $_GET['logo'] ?? __DIR__ . '/logo.png';
// 生成基礎二維碼(L 級錯誤修正)
$chl = urlencode($data);
$qrUrl = "https://chart.googleapis.com/chart?chs={$size}&cht=qr&chl={$chl}&chld=L|1&choe=UTF-8";
$qr = imagecreatefrompng($qrUrl);
// 疊加 Logo
if ($logoPath && file_exists($logoPath)) {
$logo = imagecreatefromstring(file_get_contents($logoPath));
$qrW = imagesx($qr);
$qrH = imagesy($qr);
$logoW = imagesx($logo);
$logoH = imagesy($logo);
// Logo 佔二維碼 1/5 寬度,等比縮放
$logoQrW = $qrW / 5;
$scale = $logoW / $logoQrW;
$logoQrH = $logoH / $scale;
$fromX = ($qrW - $logoQrW) / 2;
$fromY = ($qrH - $logoQrH) / 2;
imagecopyresampled($qr, $logo, $fromX, $fromY, 0, 0, $logoQrW, $logoQrH, $logoW, $logoH);
imagedestroy($logo);
}
// 輸出
header('Content-Type: image/png');
imagepng($qr);
imagedestroy($qr);
| 參數 | 說明 | 建議值 |
|---|---|---|
| chs | 圖片尺寸 | 150x150 ~ 500x500 |
| chld | 錯誤修正級別|邊距 | L|1 (7% 修正、1 行邊距) |
| choe | 編碼 | UTF-8 |
endroid/qr-code (Composer) 或 phpqrcode 庫離線生成php_gd2.dll)https://
composer require endroid/qr-code
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
$qrCode = new QrCode('https://example.com');
$writer = new PngWriter();
$result = $writer->write($qrCode);
header('Content-Type: '.$result->getMimeType());
echo $result->getString();