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

Symfony 產生 QR Code 完整指南:EndroidQrCodeBundle 實作

     編輯:PHP 綜合知識

常見 QR Code 產生方式

  1. Google Chart API:簡單但依賴外部服務,已棄用。
  2. PHP QR Code 庫:純 PHP 實作,需自行管理檔案/輸出。

Symfony 整合方案:EndroidQrCodeBundle

提供 Twig 擴充、快取、多種輸出格式,整合度最高。

安裝

composer require endroid/qrcode-bundle

註冊 Bundle

// app/AppKernel.php
new Endroid\Bundle\QrCodeBundle\EndroidQrCodeBundle(),

路由設定

# app/config/routing.yml
EndroidQrCodeBundle:
    resource: "@EndroidQrCodeBundle/Controller/"
    type: annotation
    prefix: /qrcode

設定檔 (config.yml)

endroid_qr_code:
    size: 100
    padding: 10
    extension: gif
    error_correction_level: high
    foreground_color: { r: 0, g: 0, b: 0, a: 0 }
    background_color: { r: 255, g: 255, b: 255, a: 0 }
    # label: "My label"
    # labelFontSize: 16

Twig 使用範例


{# 指定副檔名 #}


{# 自訂尺寸 #}


{# 產生 Data URI (Base64) 直接內嵌 #}
}

控制器中產生並回傳二進位

use Endroid\QrCode\QrCode;

public function qrAction($text)
{
    $qrCode = new QrCode($text);
    $qrCode->setSize(300);
    $qrCode->setPadding(10);
    $qrCode->setErrorCorrectionLevel('high');

    // 直接輸出圖片
    $response = new Response($qrCode->writeString(), 200, [
        'Content-Type' => $qrCode->getContentType(),
    ]);
    return $response;

    // 或儲存檔案
    // $qrCode->writeFile(__DIR__ . '/../../../web/qrcode.png');
}

進階應用

  • 產生含 Logo 的 QR Code:$qrCode->setLogoPath($logoPath); $qrCode->setLogoWidth(50);
  • 批次產生:搭配快取機制避免重複運算。
  • API 端點:回傳 JSON 含 data_uri 或檔案下載連結。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved