php 视频压缩ffmpeg


   $save_dir = storage_path('app') . '/public/' . mt_rand(99, 999) . time() . '_video' . ".mp4"; //保存原视频
      $out_dir = storage_path('app') . '/public/' . mt_rand(99, 999) . time() . '_smallVideo' . ".mp4"; //压缩后的视频
  $rs_video = $this->reduceVideo($oss_url, $out_dir, $save_dir);
  if ($rs_video == false) {
      continue; //压缩视频失败
  }





 //视频压缩
    public function reduceVideo($oss_url,$out_dir,$save_dir){
        $r = file_put_contents($save_dir, file_get_contents($oss_url));
        if(!$r) return  false;
        $toSize = "8M"; //最大不超过8M
        //判断文件大小
        $file_size = filesize($save_dir);
        $file_size = intval($file_size / 1048576);
        if($file_size < 9){
            $str =  base64_encode(file_get_contents($save_dir));
            @unlink($save_dir);//删除本地
            return $str; // 小于9m直接返回保存地址
        }
        // -y 自动确认覆盖  -s 压缩后分辨率 -b:v 视频码率  -fs $toSize 最大视频大小,超过后裁剪
        $shell = "ffmpeg -i " . $save_dir . " -y  -s 360x640 -b:v 862k  -fs " . $toSize . "  ". $out_dir . " 2>&1";
        exec($shell, $output, $ret);
        if($ret == 0){
            //ret 压缩执行成功返回0 执行失败返回1
            $str =  base64_encode(file_get_contents($out_dir));
            @unlink($out_dir);//删除本地
            @unlink($save_dir);//删除本地
            return $str;
        }else{
            if(file_exists($save_dir))    @unlink($save_dir);//删除本地
            return  false;
        }
    }



function reduceImage($image_path,$ossClient){
    $file_info = $ossClient->getObject(
        config('filesystems.disks.oss-private.bucket'),
        $image_path,
        [OssClient::OSS_PROCESS=>'image/info']
    );
    $file_info = json_decode($file_info,true);
    $file_size = $file_info['FileSize']['value'] / 1024;
    $rate = 100;
    if ($file_size > 1024){
        $rate = floor(1024 / $file_size * (100 - (350 / $file_size * 100)));
    }
    $options = [
        OssClient::OSS_PROCESS => "image/resize,p_{$rate}"
    ];
    $image_path = $ossClient->signUrl(
        config('filesystems.disks.oss-private.bucket'),
        $image_path,
        600,
        OssClient::OSS_HTTP_GET,
        $options
    );
    return $image_path;
}

posted @ 2022-08-11 18:56  Bashuslovakia  阅读(799)  评论(0编辑  收藏  举报