萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 產生 QR Code 兩大方案:Google Chart API 與 PHP QR Code 類庫完整教學

QR Code 應用日益普及,PHP 開發者常需在專案中動態產生二維碼。本文介紹兩種主流方案:呼叫 Google Chart API(零依賴、即時生成)與使用 PHP QR Code 類庫(離線、可嵌入 Logo),並詳細說明帶 Logo 進階技巧。

方案一:Google Chart API 快速生成

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");
?>

參數說明

  • chs:圖片尺寸(寬x高),單位像素
  • chld:錯誤修正等級 | 邊距。等級:L(7%)、M(15%)、Q(25%)、H(30%)
  • chl:編碼內容,需 URL encode

方案二:PHP QR Code 類庫(離線生成)

官網:phpqrcode.sourceforge.net,需 PHP 啟用 GD2 擴充。

基本用法

<?php
include 'phpqrcode.php';
QRcode::png('https://www.example.com');  // 直接輸出圖片至瀏覽器
?>

進階:產生帶 Logo 的 QR Code

原理:先生成 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" />';
?>

錯誤修正等級選擇建議

等級修正能力適用場景
L7%一般用途、網址較短
M15%含 Logo、中等長度內容
Q25%高可靠度需求
H30%惡劣環境、大量資料

方案比較與選擇

  • Google API:零維護、適合低流量、需網路連線、有速率限制
  • PHP QR Code:完全離線、可客製化、適合高流量、需 GD 支援

根據專案需求選擇適合方案,若需品牌化呈現,帶 Logo 方案能顯著提升辨識度與專業形象。

copyright © 萬盛學電腦網 all rights reserved