php实现七牛云相关操作

码界追光者
• 阅读 2220

一:下载七牛云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
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
6个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Peter20 Peter20
4年前
mysql中like用法
like的通配符有两种%(百分号):代表零个、一个或者多个字符。\(下划线):代表一个数字或者字符。1\.name以"李"开头wherenamelike'李%'2\.name中包含"云",“云”可以在任何位置wherenamelike'%云%'3\.第二个和第三个字符是0的值wheresalarylike'\00%'4\
Wesley13 Wesley13
3年前
Typora+图床详解(小白都能学得会)
1了解工作博客中用的笔记软件——Typora(Markdown语法)博客中用的图床——阿里云对象存储(ObjectStorageService,简称OSS)图床平台介绍七牛云七牛云(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fporta
Stella981 Stella981
3年前
Linux系统定时备份网站文件到七牛云存储脚本
1、七牛云账号注册。有些朋友可能会问为什么要备份到七牛云?很简单,七牛云免费注册就能获取1G的存储空间,只要简单几步操作完成实名认证即可获取10G的存储空间,对于一般个人站点来说已经足够备份使用了。如果还没有七牛云存储空间的请参照此教程申请并完成实名认证:【七牛云注册】(https://www.oschina.net/actio
Wesley13 Wesley13
3年前
thinphp php 七牛云sdk 图片上传
安装七牛云sdk图片上传在项目根目录下phpcomposer.pharrequireqiniu/phpsdk,或者composerrequireqiniu/phpsdk等待即可完成。在vendor下可以看到qiniu目录在七牛云账号设置里面找到自己的ak和sdk
Wesley13 Wesley13
3年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这