二維碼已廣泛應用於移動支付、登錄授權、名片分享、設備綁定等場景。本文介紹兩種主流 PHP 生成二維碼方案:調用 Google Chart API(無需本地依賴)與使用 PHP QR Code 庫(離線生成、可嵌入 Logo),並提供完整可運行代碼。
優點:零依賴、無需維護、支持多種圖表類型。缺點:需外網訪問、有調用頻率限制、數據經過第三方。
<?php
/**
* 使用 Google Chart API 生成二維碼
* @param string $content 二維碼內容
* @param int $size 圖片寬高(像素),默認 150
* @param string $level 纠錯級別 L/M/Q/H,默認 L
* @param int $margin 邊距,默認 0
* @return string 圖片 HTML 標簽
*/
function generateQRFromGoogle(string $content, int $size = 150, string $level = 'L', int $margin = 0): string {
$params = http_build_query([
'chs' => "{$size}x{$size}",
'cht' => 'qr',
'chl' => $content,
'choe' => 'UTF-8',
'chld' => "{$level}|{$margin}",
]);
return '<img src="https://chart.googleapis.com/chart?' . $params . '" alt="QR Code" />';
}
// 使用示例
echo generateQRFromGoogle('https://www.example.com', 200, 'M', 1);
?>
| 參數 | 說明 | 可選值 |
|---|---|---|
| chs | 圖片尺寸 | 如 200x200,最大 500x500 |
| cht | 圖表類型 | qr = 二維碼 |
| chl | 編碼內容 | URL、文本、JSON 等,需 URL 編碼 |
| choe | 字符編碼 | UTF-8 推薦 |
| chld | 纠錯級別|邊距 | L|0, M|1, Q|2, H|3 |
優點:完全離線、無頻率限制、可自定義樣式、支持嵌入 Logo。缺點:需安裝庫、消耗服務器資源。
# Composer 安裝(推薦)
composer require endroid/qrcode
# 或下載原版庫
# https://sourceforge.net/projects/phpqrcode/
<?php
require_once 'phpqrcode/phpqrcode.php';
$value = 'https://www.example.com';
$errorCorrectionLevel = 'L'; // L(7%) M(15%) Q(25%) H(30%)
$matrixPointSize = 4; // 每個模塊像素大小
$margin = 2; // 邊距模塊數
// 直接輸出到瀏覽器
QRcode::png($value, false, $errorCorrectionLevel, $matrixPointSize, $margin);
// 保存到文件
QRcode::png($value, 'qrcode.png', $errorCorrectionLevel, $matrixPointSize, $margin);
?>
<?php
require_once 'phpqrcode/phpqrcode.php';
function generateQRWithLogo(string $content, string $logoPath, string $outputPath = false): void {
// 1. 生成基礎二維碼(高纠錯級別 H,確保遮蓋 Logo 仍可識別)
QRcode::png($content, 'temp_qr.png', 'H', 6, 2);
$qr = imagecreatefrompng('temp_qr.png');
$logo = imagecreatefromstring(file_get_contents($logoPath));
if (!$qr || !$logo) {
throw new Exception('圖片載入失敗');
}
$qrWidth = imagesx($qr);
$qrHeight = imagesy($qr);
$logoWidth = imagesx($logo);
$logoHeight = imagesy($logo);
// 2. 計算 Logo 尺寸(佔二維碼 1/5,保證識別率)
$logoMaxWidth = $qrWidth / 5;
$logoMaxHeight = $qrHeight / 5;
$scale = min($logoMaxWidth / $logoWidth, $logoMaxHeight / $logoHeight);
$newLogoWidth = (int)($logoWidth * $scale);
$newLogoHeight = (int)($logoHeight * $scale);
// 3. 創建縮放後的 Logo(保持透明度)
$logoResized = imagecreatetruecolor($newLogoWidth, $newLogoHeight);
imagealphablending($logoResized, false);
imagesavealpha($logoResized, true);
imagecopyresampled($logoResized, $logo, 0, 0, 0, 0, $newLogoWidth, $newLogoHeight, $logoWidth, $logoHeight);
// 4. 計算居中位置
$x = ($qrWidth - $newLogoWidth) / 2;
$y = ($qrHeight - $newLogoHeight) / 2;
// 5. 合成:先畫白色背景圓角矩形,再疊加 Logo
$bgColor = imagecolorallocatealpha($qr, 255, 255, 255, 0);
imagefilledroundedrect($qr, $x-2, $y-2, $x+$newLogoWidth+2, $y+$newLogoHeight+2, 5, $bgColor);
imagecopy($qr, $logoResized, $x, $y, 0, 0, $newLogoWidth, $newLogoHeight);
// 6. 輸出
if ($outputPath) {
imagepng($qr, $outputPath);
} else {
header('Content-Type: image/png');
imagepng($qr);
}
// 7. 清理資源
imagedestroy($qr);
imagedestroy($logo);
imagedestroy($logoResized);
@unlink('temp_qr.png');
}
// 輔助函數:畫圓角矩形
function imagefilledroundedrect($img, $x1, $y1, $x2, $y2, $radius, $color) {
// 簡易實現:畫矩形 + 四個圓角
imagefilledrectangle($img, $x1+$radius, $y1, $x2-$radius, $y2, $color);
imagefilledrectangle($img, $x1, $y1+$radius, $x2, $y2-$radius, $color);
imagefilledellipse($img, $x1+$radius, $y1+$radius, $radius*2, $radius*2, $color);
imagefilledellipse($img, $x2-$radius, $y1+$radius, $radius*2, $radius*2, $color);
imagefilledellipse($img, $x1+$radius, $y2-$radius, $radius*2, $radius*2, $color);
imagefilledellipse($img, $x2-$radius, $y2-$radius, $radius*2, $radius*2, $color);
}
// 使用
generateQRWithLogo('https://www.example.com', 'logo.png', 'qr_with_logo.png');
?>
| 維度 | Google Chart API | PHP QR Code |
|---|---|---|
| 部署複雜度 | 零配置 | 需引入庫文件 |
| 網絡依賴 | 必須聯網 | 完全離線 |
| 並發性能 | 依賴 Google 服務器 | 消耗本地 CPU/內存 |
| 自定義樣式 | 僅支持基本參數 | 支持 Logo、顏色、形狀、圓點風格 |
| 數據隱私 | 內容傳給 Google | 數據不出服務器 |
| 適用場景 | 低頻、非敏感、快速原型 | 高頻、敏感數據、定制化需求 |
目前更推薦使用現代化、PSR-4 標準的 endroid/qrcode 庫:
<?php
require 'vendor/autoload.php';
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Writer\PngWriter;
$qrCode = new QrCode('https://www.example.com');
$qrCode->setSize(300)
->setMargin(10)
->setErrorCorrectionLevel('high')
->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0])
->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255]);
$writer = new PngWriter();
$result = $writer->write($qrCode);
// 直接輸出
header('Content-Type: ' . $result->getMimeType());
echo $result->getString();
// 或保存文件
file_put_contents('qrcode_modern.png', $result->getString());
?>
根據業務場景選擇合適方案:內網管理系統、高併發 API 服務首選本地庫;快速原型、低頻頁面可用 Google API。現代項目建議採用 endroid/qrcode 獲得更好的維護性與擴展性。