ThinkPHP 3.2 內建無二維碼庫,透過 Vendor 機制整合 phpqrcode 可快速實現生成二維碼、嵌入 Logo 等功能。本文從下載、目錄結構、基本生成、Logo 合成四步完整示範。
ThinkPHP/Library/Vendor/phpqrcode/ 目錄下,確保 phpqrcode.php 位於該資料夾根目錄。<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
public function qrcode($url = 'www.baidu.com', $level = 3, $size = 4) {
// 載入類庫
Vendor('phpqrcode.phpqrcode');
$errorCorrectionLevel = intval($level); // L=1, M=2, Q=3, H=4
$matrixPointSize = intval($size); // 圖片尺寸倍數
// 直接輸出到瀏覽器
$qr = new \QRcode();
$qr->png($url, false, $errorCorrectionLevel, $matrixPointSize, 2);
}
}
?>
訪問 https://domain/Index/qrcode 即可看到二維碼圖片。
<?php
include 'phpqrcode.php'; // 確保路徑正確
$value = 'https://www.example.com/';
$errorCorrectionLevel = 'H'; // 高容錯,利於 Logo 遮蓋
$matrixPointSize = 8; // 較大尺寸,確保 Logo 清晰
// 1. 先生成基礎二維碼暫存檔
$qrFile = 'qrcode.png';
\QRcode::png($value, $qrFile, $errorCorrectionLevel, $matrixPointSize, 2);
// 2. 載入二維碼與 Logo
$qrImg = imagecreatefromstring(file_get_contents($qrFile));
$logoImg = imagecreatefromstring(file_get_contents('logo.png')); // 需預備 logo.png
// 3. 計算 Logo 目標尺寸(二維碼寬度 1/5)
$qrW = imagesx($qrImg);
$qrH = imagesy($qrImg);
$logoW = imagesx($logoImg);
$logoH = imagesy($logoImg);
$targetW = $qrW / 5;
$scale = $logoW / $targetW;
$targetH = $logoH / $scale;
// 4. 置中合成
$dstX = ($qrW - $targetW) / 2;
$dstY = ($qrH - $targetH) / 2;
imagecopyresampled($qrImg, $logoImg, $dstX, $dstY, 0, 0, $targetW, $targetH, $logoW, $logoH);
// 5. 輸出或儲存
imagepng($qrImg, 'final_qrcode.png');
imagedestroy($qrImg);
imagedestroy($logoImg);
echo '<img src="final_qrcode.png">';
?>
| 參數 | 建議值 | 說明 |
|---|---|---|
| errorCorrectionLevel | H (或 4) | 高容錯率(30%),Logo 遮蓋不影響掃描 |
| matrixPointSize | 6~10 | 尺寸倍數,Logo 合成建議 ≥6 保證清晰度 |
| Logo 佔比 | 1/4 ~ 1/5 | 過大導致掃描失敗,過小辨識度低 |
| Logo 格式 | PNG 透明背景 | 避免白底遮蓋定位點 |
Vendor('phpqrcode.phpqrcode') 路徑與檔名大小寫。header('Content-Type: image/png'),且前無任何輸出(含 BOM、空白行)。memory_limit,適當調大或分塊處理。PHPExcel 導出含二維碼的 Excel 列印清單。