php實現七牛雲相關操作

huaweichenai發表於2022-01-07

一:下載七牛雲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

相關文章