您的当前位置:首页>全部文章>文章详情

php二维码类

发表于:2024-04-19 10:45:40浏览:279次TAG: #二维码

前言

本文将详细介绍如何使用php生成二维码,并提供整理的源码和通过示例代码进行说明。

示例

// 调用
//$qrcode = \app\common\utils\Qrcode::build('你好,大字节',ROOT_PATH . 'public/qrcode/q1234.png');
//dump($qrcode); //输出=>string(77) "/www/wwwroot/xx.xx.xx/public/qrcode/q1234.png"

<?php
namespace app\common\utils;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Label\Alignment\LabelAlignmentCenter;
use Endroid\QrCode\Label\Font\NotoSans;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;

/**
 * 二维码类
 * PHP版本:^7.3||^8.0
 * 安装命令: composer require endroid/qr-code:4.3.0
 */
class Qrcode {
    /**
     * 生成二维码
     * @param $params
     * @param $filename 若为保存文件名:ROOT_PATH . '/public/qrcode/qrcode.png'
     *                  若为null,则表示返回base64 格式的图片
     * @return mixed
     */
    public static function build($params,$filename = null)
    {
        if (is_string($params)){
            $data = $params;
            $params = [];
        }
        else {
            $data = $params['data'];
        }
        $that = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            // 二维码文本
            ->data($data)
            // 内容编码
            ->encoding(new Encoding('UTF-8'))
            // 容错等级(越高二维码越密集)
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            // 二维码内容区域大小
            ->size($params['size'] ?? 300)
            // 二维码内容外边距大小
            ->margin($params['margin'] ?? 10)
            // 二维码内容圆形块尺寸模型
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin());
        if (!empty($params['logo'])){
            // 二维码中间区域logo图片
            $that = $that->logoPath($params['logo'] ?? '')
                ->logoResizeToWidth($params['logo_width'] ?? 100)
                ->logoResizeToHeight($params['logo_height'] ?? 100);
        }
        // 二维码下方文字
        $that = $that->labelText($params['label'] ?? '')
            ->labelFont(new NotoSans(20))
            ->labelAlignment(new LabelAlignmentCenter())
            // 验证读取器(默认情况下禁用)
            ->validateResult(false);
        // 执行生成器
        $result = $that->build();
        // 将二维码图片保存到本地服务器
        if (!is_null($filename)) {
            $dir = dirname($filename);
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }
            $result->saveToFile($filename);
            return $filename;
        }
        else {
            // 返回 base64 格式的图片
            $dataUri = $result->getDataUri();
            return $dataUri;
        }
    }
}