首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 生成二維碼完整方案:Google Chart API 與 PHP QR Code 庫實戰

     編輯:PHP 相關知識

二維碼已廣泛應用於移動支付、登錄授權、名片分享、設備綁定等場景。本文介紹兩種主流 PHP 生成二維碼方案:調用 Google Chart API(無需本地依賴)與使用 PHP QR Code 庫(離線生成、可嵌入 Logo),並提供完整可運行代碼。

方案一:Google Chart API(雲端生成)

優點:零依賴、無需維護、支持多種圖表類型。缺點:需外網訪問、有調用頻率限制、數據經過第三方。

核心代碼

<?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

方案二:PHP QR Code 庫(本地生成)

優點:完全離線、無頻率限制、可自定義樣式、支持嵌入 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);
?>

進階:二維碼中心嵌入 Logo

<?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 APIPHP QR Code
部署複雜度零配置需引入庫文件
網絡依賴必須聯網完全離線
並發性能依賴 Google 服務器消耗本地 CPU/內存
自定義樣式僅支持基本參數支持 Logo、顏色、形狀、圓點風格
數據隱私內容傳給 Google數據不出服務器
適用場景低頻、非敏感、快速原型高頻、敏感數據、定制化需求

現代替代方案:Endroid/QrCode (Composer)

目前更推薦使用現代化、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());
?>

生產環境優化建議

  1. 緩存機制:相同內容的二維碼緩存到 Redis/文件,避免重複生成
  2. 異步生成:大量生成時放入隊列,Worker 後台處理
  3. 驗證識別率:嵌入 Logo 後務必用多款掃碼 App 測試(微信、支付寶、iOS 相機)
  4. 錯誤糾正級別選擇:嵌入 Logo 必須用 H 級(30%),純數據可用 M 級(15%)平衡大小與健壯性

根據業務場景選擇合適方案:內網管理系統、高併發 API 服務首選本地庫;快速原型、低頻頁面可用 Google API。現代項目建議採用 endroid/qrcode 獲得更好的維護性與擴展性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved