PHP-生成二維碼(qr-code)

1.爲何要寫這篇文章

最近作項目要生成二維碼讓用戶作跳轉,搜索了一下發現網上都是用一個叫作 phpqrcode 的擴展,在 github 上搜索了一下發現這個項目做者在6年前就已經沒有維護了,百度的文章也是千篇一概的你複製個人我複製你的,因此只好在 github 上看看有沒有更好的關於 PHP 生成二維碼的擴展,以後找到了一個項目名稱爲 qr-code 的擴展,感受不錯,做者也一直在作維護,使用也是簡單方便。因此在這裏把這個擴展的安裝使用說明一下,方便各位的開發。php

qr-code 項目的github 地址爲:qr-codehtml

2.安裝 qr-code

這裏咱們經過composer 來安裝擴展,composer 也算是如今比較火的包管理工具了,若是對composer 不太瞭解的話,能夠看下我之前的文章:前端

《php-composer的安裝與使用方法》linux

個人環境爲 linux,咱們鍵入如下命令來進行該擴展的安裝:git

composer require endroid/qr-code

clipboard.png

當擴展安裝完畢後,咱們就能夠開始下面的操做了。github

3.生成二維碼

首先咱們須要在項目中引入qr-code 類文件,composer 如今基本上是經過psr-4 "命名空間": "路徑" 的方式進行自動加載,它的位置位於擴展根目錄的 composer.json 文件中。json

好了,如今咱們引入qr-code 類文件,並嘗試輸出一個簡單的二維碼。segmentfault

use Endroid\QrCode\QrCode;

// $content 通常爲url地址 固然也能夠是文字內容
$content = 'http://www.baidu.com?rand=' . rand(1000, 9999);
$qrCode = new QrCode($content);
// 指定內容類型
header('Content-Type: '.$qrCode->getContentType());
// 輸出二維碼
echo $qrCode->writeString();

好了,當指定了內容類型後,會直接在頁面輸出二維碼composer

clipboard.png

那這種直接輸出的二維碼怎麼應用於項目中呢,通常都是直接寫在html 中的 <img> 標籤中,例如:工具

<img src="http://localhost:8080/projecttest/qrtest?id=1234"  alt="這是一個二維碼" />

clipboard.png

這樣,就能夠把二維碼顯示在頁面的任意位置了。固然,咱們也能夠把它存入文件中,生成一個任意格式的圖片,好比說:

$qrCode->writeFile(__DIR__ . '/qrcode.png');

這樣咱們就能夠根據圖片路徑在頁面上展現二維碼了

4.簡單的示例文件以及經常使用參數介紹

這裏,我貼出一個簡單的類處理文件,並介紹一下qr-code 經常使用的一些參數。

類文件:

namespace '命名空間';

use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment;
use Endroid\QrCode\QrCode;

class QrcodeComponent
{
    protected $_qr;
    protected $_encoding = 'UTF-8';
    protected $_size = 300;
    protected $_logo = false;
    protected $_logo_url = '';
    protected $_logo_size = 80;
    protected $_title = false;
    protected $_title_content = '';
    protected $_generate = 'display'; // display-直接顯示 writefile-寫入文件
    const MARGIN = 10;
    const WRITE_NAME = 'png';
    const FOREGROUND_COLOR = ['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0];
    const BACKGROUND_COLOR = ['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0];

    public function __construct($config) {
        isset($config['generate']) && $this->_generate = $config['generate'];
        isset($config['encoding']) && $this->_encoding = $config['encoding'];
        isset($config['size']) && $this->_size = $config['size'];
        isset($config['display']) && $this->_size = $config['size'];
        isset($config['logo']) && $this->_logo = $config['logo'];
        isset($config['logo_url']) && $this->_logo_url = $config['logo_url'];
        isset($config['logo_size']) && $this->_logo_size = $config['logo_size'];
        isset($config['title']) && $this->_title = $config['title'];
        isset($config['title_content']) && $this->_title_content = $config['title_content'];
    }

    /**
     * 生成二維碼
     * @param $content 須要寫入的內容
     * @return array | page input
     */
    public function create($content) {
        $this->_qr = new QrCode($content);
        $this->_qr->setSize($this->_size);
        $this->_qr->setWriterByName(self::WRITE_NAME);
        $this->_qr->setMargin(self::MARGIN);
        $this->_qr->setEncoding($this->_encoding);
        $this->_qr->setErrorCorrectionLevel(ErrorCorrectionLevel::HIGH);
        $this->_qr->setForegroundColor(self::FOREGROUND_COLOR);
        $this->_qr->setBackgroundColor(self::BACKGROUND_COLOR);
        if ($this->_title) {
            $this->_qr->setLabel($this->_title_content, 16, '字體地址', LabelAlignment::CENTER);
        }
        if ($this->_logo) {
            $this->_qr->setLogoPath($this->_logo_url);
            $this->_qr->setLogoWidth($this->_logo_size);
            $this->_qr->setRoundBlockSize(true);
        }
        $this->_qr->setValidateResult(false);

        if ($this->_generate == 'display') {
            // 前端調用 例:<img src="http://localhost/qr.php?url=base64_url_string">
            header('Content-Type: ' . $this->_qr->getContentType());
            return $this->_qr->writeString();
        } else if ($this->_generate == 'writefile') {
            return $this->_qr->writeString();
        } else {
            return ['success' => false, 'message' => 'the generate type not found', 'data' => ''];
        }
    }

    /**
     * 生成文件
     * @param $file_name 目錄文件 例: /tmp
     * @return array
     */
    public function generateImg($file_name) {
        $file_path = $file_name . DS . uniqid() . '.' . self::WRITE_NAME;

        if (!file_exists($file_name)) {
            mkdir($file_name, 0777, true);
        }

        try {
            $this->_qr->writeFile($file_path);
            $data = [
                'url' => $file_path,
                'ext' => self::WRITE_NAME,
            ];
            return ['success' => true, 'message' => 'write qrimg success', 'data' => $data];
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage(), 'data' => ''];
        }
    }
}

使用方法:

use '命名空間';

$qr_url = 'http://www.baidu.com?id=' . rand(1000, 9999);
$file_name = '/tmp';

// 直接輸出
$qr_code = new QrcodeComponent();
$qr_img = qr_code->create($qr_url);
echo $qr_img;

// 生成文件
$config = [
    'generate' => 'writefile',
];
$qr_code = new QrcodeComponent($config);
$qr_img = $qr_code->create($qr_url);
$rs = $qr_code->generateImg($file_name);
print_r($rs);

經常使用參數解釋:

setSize - 二維碼大小 px
setWriterByName - 寫入文件的後綴名
setMargin - 二維碼內容相對於整張圖片的外邊距
setEncoding - 編碼類型
setErrorCorrectionLevel - 容錯等級,分爲L、M、Q、H四級
setForegroundColor - 前景色
setBackgroundColor - 背景色
setLabel - 二維碼標籤
setLogoPath - 二維碼logo路徑
setLogoWidth - 二維碼logo大小 px

相關文章
相關標籤/搜索