关于php:php实现七牛云相关操作

36次阅读

共计 5927 个字符,预计需要花费 15 分钟才能阅读完成。

一:下载七牛云 SDK

composer require qiniu/php-sdk

二:php 实现七牛云 demo

<?php

namespace common\helpers;

use common\models\Config;
use common\models\VideoApiLog;
use Qiniu\Auth;
use Qiniu\Processing\PersistentFop;
use Qiniu\Storage\UploadManager;
use Yii;
use yii\helpers\ArrayHelper;
use common\helpers\Universal;
use yii\helpers\FileHelper;
use yii\httpclient\Client;
use yii\web\ServerErrorHttpException;
use function Qiniu\base64_urlSafeEncode;

/**
 * 七牛云解决
 *
 * @author wangjian
 * @since 0.1
 */
class QiNiu
{
    /**
     * @var string accessKey
     */
    public $accessKey;

    /**
     * @var string accessKey
     */
    public $secretKey;

    /**
     * @var string bucket
     */
    public $bucket;

    /**
     * @var string url
     */
    public $url;

    /**
     * @var string pipeline
     */
    public $pipeline;

    // 过程状态
    const STATUS_SUCCESS = 0;// 胜利
    const STATUS_WAIT = 1;// 期待
    const STATUS_GO = 2;// 执行中
    const STATUS_ERROR = 3;// 失败

    /**
     * 初始化
     */
    public function __construct()
    {
        $this->accessKey = "";
        $this->secretKey = "";
        $this->bucket = "";
        $this->url = "";
        $this->pipeline = "";
    }

    /**
     * 获取上传 token
     */
    public function getToken()
    {$auth = new Auth($this->accessKey, $this->secretKey);
        // 生成上传 Token
        $token = $auth->uploadToken($this->bucket);
        return $token;
    }

    /**
     * 上传
     */
    public function upload($file, $saveFileName = null)
    {$token = $this->getToken();
        $uploadMgr = new UploadManager();

        if ($saveFileName === null) {$pathinfo = is_array($file) ? pathinfo($file['name']) : $file;
            $extension = $pathinfo['extension'];
            $saveFileName = Yii::$app->getSecurity()->generateRandomString() . '-' . date('His',time()) .".".$extension;
        }
        // 上传到七牛云后 保留的文件名
        $tmpName = is_array($file) ? $file['tmp_name'] : $file;
        list($result, $err) = $uploadMgr->putFile($token,$saveFileName,$tmpName);
        if ($err !== null) {return false;}

        return [
            'file' => $saveFileName,
            'url' => $this->url . $saveFileName,
        ];
    }

    /**
     * 获取已上传音视频元信息
     */
    public function getAvinfo($file)
    {$client = new Client();
        $response = $client->createRequest()
            ->setMethod('post')
            ->setUrl($this->url . $file . '?avinfo')      // 申请地址
            ->send();
        if ($response->isOk) {return $response->data;}
        return [];}


    /**
     * 获取过程解决状态
     */
    public function persistentStatus($persistentId)
    {$auth = new Auth($this->accessKey, $this->secretKey);
        $config = new \Qiniu\Config();
        $pfop = new PersistentFop($auth, $config);
        list($result, $error) = $pfop->status($persistentId);
        if ($error != null)
        {return self::STATUS_ERROR;}
        $code = isset($result['code']) ? $result['code'] : 3;
        return $code;
    }

    /**
     * 获取视频指定帧图片
     */
    public function getVideoImage($file, $saveFile = null, $offset = 1)
    {$auth = new Auth($this->accessKey, $this->secretKey);
        $config = new \Qiniu\Config();
        $pfop = new PersistentFop($auth, $config);
        if ($saveFile == null) {$fileName = basename($file);
            $pathinfo = pathinfo($fileName);
            $saveFile = $pathinfo['filename'] . '.jpg';
        }
        $entry = base64_urlSafeEncode("$this->bucket:$saveFile");
        $fops = "vframe/jpg/offset/". $offset ."|saveas/$entry";
        $pipeline = null;
        if ($this->pipeline) {$pipelineArr = explode(',', $this->pipeline);
            $pipeline = $pipelineArr[array_rand($pipelineArr,1)];
        }
        list($id, $err) = $pfop->execute($this->bucket, $file, $fops, $pipeline);
        if ($err != null)
        {return false;}

        // 查问过程状态
        $persistentStatus = false;
        $code = self::STATUS_ERROR;
        while ($persistentStatus === false) {sleep(1);
            $code = $this->persistentStatus($id);
            if (in_array($code,[self::STATUS_SUCCESS, self::STATUS_ERROR])) {$persistentStatus = true;}
        }

        if ($code == self::STATUS_SUCCESS) {
            return [
                'url' => $this->url . $saveFile,
                'file' => $saveFile
            ];
        }
        return false;
    }

    /**
     * 视频解决
     */
    public function avthumb($file, $saveFileName = null, $param = [])
    {if (empty($param)) {return false;}

        $auth = new Auth($this->accessKey, $this->secretKey);
        $config = new \Qiniu\Config();
        $pfop = new PersistentFop($auth, $config);


        $pathinfo = pathinfo($file);
        $extension = strtolower($pathinfo['extension']);
        if ($saveFileName === null) {$saveFileName = Yii::$app->getSecurity()->generateRandomString() . '-' . date('His',time()) .".".$extension;
        }

        $entry = base64_urlSafeEncode("$this->bucket:$saveFileName");
        $fops = "avthumb/" . $extension;

        // 裁剪
        $star = isset($param['star']) ? $param['star'] : 0;
        $end = isset($param['end']) ? $param['end'] : 0;
        $star = intval($star);
        $end = intval($end);
        if (!((empty($star) && empty($end)) || ($star >= $end))) {
            // 须要裁剪
            $duration = $end - $star;
            if (!empty($duration)) {$fops .= "/ss/". $star ."/t/" . $duration;/* 截取片段 */}
        }

        // 文字水印
        $wmText = isset($param['wmText']) ? $param['wmText'] : '';
        if ($wmText) {$fops .= "/wmText/". base64_urlSafeEncode($wmText);
            // 透明度
            $wmAlpha = isset($param['wmAlpha']) ? $param['wmAlpha'] : '1.0';
            $fops .= "/wmAlpha/". $wmAlpha;
            // 字体
            $wmFont = isset($param['wmFont']) ? $param['wmFont'] : '宋体';
            $wmFont = base64_urlSafeEncode($wmFont);
            $fops .= "/wmFont/". $wmFont;

            // 水印色彩
            $wmFontColor = isset($param['wmFontColor']) ? $param['wmFontColor'] : '#ffffff';
            $wmFontColor = base64_urlSafeEncode($wmFontColor);
            $fops .= "/wmFontColor/". $wmFontColor;

            // 水印文字大小
            $wmFontSize = isset($param['wmFontSize']) ? $param['wmFontSize'] : '30';
            $fops .= "/wmFontSize/". $wmFontSize;

            // 水印文字地位
            $wmGravityText = isset($param['wmGravityText']) ? $param['wmGravityText'] : 'SouthWest';// 方位
            $wmOffsetX = isset($param['wmOffsetX']) ? $param['wmOffsetX'] : '0';// X 偏移量
            $wmOffsetY = isset($param['wmOffsetY']) ? $param['wmOffsetY'] : '0';// Y 偏移量
            $fops .= "/wmGravityText/". $wmGravityText . "/wmOffsetX/" . $wmOffsetX . "/wmOffsetY/" . $wmOffsetY;
        }

        $audio = isset($param['audio']) ? $param['audio'] : '';
        // 音频
        if ($audio) {$fops .= "/multiArep/" . base64_urlSafeEncode('kodo://'. $this->bucket .'/' . $audio);
        }
        $fops .= "|saveas/$entry";
        $pipeline = null;
        if ($this->pipeline) {$pipelineArr = explode(',', $this->pipeline);
            $pipeline = $pipelineArr[array_rand($pipelineArr,1)];
        }
        list($persistentId, $err) = $pfop->execute($this->bucket, $file, $fops, $pipeline);

        if ($err != null)
        {return false;}

        // 查问过程状态
        $persistentStatus = false;
        $code = self::STATUS_ERROR;
        while ($persistentStatus === false) {sleep(1);
            $code = $this->persistentStatus($persistentId);
            if (in_array($code,[self::STATUS_SUCCESS, self::STATUS_ERROR])) {$persistentStatus = true;}
        }

        if ($code == self::STATUS_SUCCESS) {
            return [
                'file' => $saveFileName,
                'url' => $this->url . $saveFileName,
                'duration' => $duration,
            ];
        }
        return false;
    }


}

将其中的 accessKey,secretKey,bucket,url,pipeline 参数换成你本人七牛云账号的信息

三:简略实现

1:实现上传

$qiniu = new QiNiu();
$qiniu->upload($_FILES['file']);

2:获取上传的音视频信息

$file = '';// 上传七牛云后文件名
$qiniu = new QiNiu();
$qiniu->getAvinfo($file);

3: 获取视频指定帧图片

$file = '';// 上传七牛云后视频名称
$qiniu = new QiNiu();
$qiniu->getVideoImage($file);// 其余参数参考 demo

4: 视频解决 (裁剪,文字水印,增加音频)

$file = '';// 上传七牛云后视频名称
$qiniu = new QiNiu();
$qiniu->avthumb($file);// 其余参数参考 demo

正文完
 0