1. 程式人生 > >tp5 thinkphp 使用phpqrcode生成二維碼

tp5 thinkphp 使用phpqrcode生成二維碼

1--下載類庫

composer require aferrandini/phpqrcode -vvv

2-common 的方法

/**
 * 功能:生成二維碼
 * @param string $qrData 手機掃描後要跳轉的網址
 * @param string $qrLevel 預設糾錯比例 分為L、M、Q、H四個等級,H代表最高糾錯能力
 * @param string $qrSize 二維碼圖大小,1-10可選,數字越大圖片尺寸越大
 * @param string $savePath 圖片儲存路徑
 * @param string $savePrefix 圖片名稱字首
 */
function createQRcode($savePath, $qrData = 'PHP QR Code :)', $qrLevel = 'L', $qrSize = 4, $savePrefix = 'qrcode')
{
    if (!isset($savePath)) return '';
    //設定生成png圖片的路徑
    $PNG_TEMP_DIR = $savePath;

    //檢測並建立生成資料夾
    if (!file_exists($PNG_TEMP_DIR)) {
        mkdir($PNG_TEMP_DIR);
    }
    $filename = $PNG_TEMP_DIR . 'test.png';
    $errorCorrectionLevel = 'L';
    if (isset($qrLevel) && in_array($qrLevel, ['L', 'M', 'Q', 'H'])) {
        $errorCorrectionLevel = $qrLevel;
    }
    $matrixPointSize = 4;
    if (isset($qrSize)) {
        $matrixPointSize = min(max((int)$qrSize, 1), 10);
    }
    if (isset($qrData)) {
        if (trim($qrData) == '') {
            die('data cannot be empty!');
        }
        //生成檔名 檔案路徑+圖片名字字首+md5(名稱)+.png
        $filename = $PNG_TEMP_DIR . $savePrefix . md5($qrData . '|' . $errorCorrectionLevel . '|' . $matrixPointSize) . '.png';
        //開始生成
        \PHPQRCode\QRcode::png($qrData, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
    } else {
        //預設生成
        \PHPQRCode\QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2);
    }
    if (file_exists($PNG_TEMP_DIR . basename($filename)))
        return basename($filename);
    else
        return FALSE;
}

3--控制器的 方法

public function test(){
            //$savePath 圖片儲存路徑
            $savePath = APP_PATH . '/../Public/qrcode/';
            //路徑
            $webPath = '/public/qrcode/';
            //$qrData 手機掃描後要跳轉的網址
            $qrData = 'http://www.baidu.com';
            // $qrLevel 預設糾錯比例 分為L、M、Q、H四個等級,H代表最高糾錯能力
            $qrLevel = 'H';
            //$qrSize 二維碼圖大小,1-10可選,數字越大圖片尺寸越大
            $qrSize = '8';
            // $savePrefix 圖片名稱字首
            $savePrefix = 'NickBai';
            if($filename = createQRcode($savePath, $qrData, $qrLevel, $qrSize, $savePrefix)){
                $pic = $webPath . $filename;
            }
           echo "<img src='$pic'>";
    }

如整合期間有遇到什麼問題 可以加群 858507220 一起討論哦。