侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

PHP调用ffmpeg对视频截图并拼接脚本

php  /  管理员 发布于 7年前   207

PHP脚本调用ffmpeg对视频截图并拼接,供大家参考,具体内容如下

目前支持MKV,MPG,MP4等常见格式的视频,其他格式有待测试

12P 一张截图平均生成时间  1.64s     100个视频,大概需要2分半左右

9P  一张截图平均生成时间  1.13s      100个视频,大概需要2分钟左右

6P  一张截图平均生成时间  0.86s      100个视频,大概需要1分半左右

3P  一张截图平均生成时间  0.54s      100个视频,大概需要1分钟左右

rootdir = dirname(__FILE__);       $count = count($this->timeArray);  for($i=1;$i<=$count;$i++)     {       $ii = $i-1;       $this->fileArray[$ii] = $this->tmp.DS.$i.".jpg";     }   }       /**   *  当前时间,精确到小数点   */   private static function microtime_float()   {     list($usec, $sec)= explode(" ", microtime());     return ((float)$usec + (float)$sec);   }      /**   *  00:00:00 时间转秒   */   private static function timeToSec($time)    {      $p = explode(':',$time);      $c = count($p);      if ($c>1)      {         $hour  = intval($p[0]);         $minute = intval($p[1]);         $sec   = intval($p[2]);      }      else      {         throw new Exception('error time format');      }      $secs = $hour * 3600 + $minute * 60 + $sec;      return $secs;    }      /**   *  00:00:00 时间转秒   */   private static function secToTime($time)    {          $hour = floor($time/3600);     $min = floor(($time - $hour * 3600)/60);     $sec = $time % 60;     $timeStr = sprintf("%02d:%02d:%02d",$hour,$min,$sec);     return $timeStr;      }       /**   *  获取全部文件   */    private function getFiles($dir)   {     $files = array();     $dir = rtrim($dir, "/\\") . DS;     $dh = opendir($dir);     if ($dh == false) { return $files; }      while (($file = readdir($dh)) != false)     {       if ($file{0} == '.') { continue; }        $path = $dir . $file;       if (is_dir($path))       {         $files = array_merge($files, $this->getFiles($path));       }       elseif (is_file($path))       {         $files[] = $path;       }     }     closedir($dh);     return $files;   }      /**   *  搜索路径   */   public function searchDir($sourcePath = NULL)   {          $this->timeStart = $this->microtime_float();      if ($sourcePath)      {       $this->rootdir = $sourcePath;     }           if (file_exists($this->rootdir) && is_dir($this->rootdir))     {       $this->files = $this->getFiles($this->rootdir.DS.$this->source);           }        $this->fileCount = count($this->files);        foreach ($this->files as $path)     {       $fi = pathinfo($path);       $flag = array_search(strtolower($fi['extension']),$this->extensionArray);       if (!$flag) continue;       $this->getScreenShoot(basename($path));     }          $this->timeEnd = $this->microtime_float();     $time = $this->timeEnd - $this->timeStart;          if($this->fileCount > 0)     {       $str = sprintf("[TOTAL]: Cost Time:%8s | Total File:[%d] | Successed:[%d] | Failed:[%d] | Speed:%.2fs per file\n",$this->secToTime($time),$this->fileCount,$this->successCount,$this->failedCount,$time/$this->fileCount);       file_put_contents("log.txt",$str,FILE_APPEND);      }     else     {       $str = sprintf("[TOTAL]: Cost Time:%8s | Total File:[%d] | Successed:[%d] | Failed:[%d] | Speed:%.2fs per file\n",$this->secToTime($time),$this->fileCount,$this->successCount,$this->failedCount,0);       file_put_contents("log.txt",$str,FILE_APPEND);     }          }      /**   *  获取视频信息   */   private function getVideoInfo($file){       $re = array();       exec(".".DS."ffmpeg -i {$file} 2>&1", $re);       $info = implode("\n", $re);  if(preg_match("/No such file or directory/i", $info))       {         return false;       }  if(preg_match("/Invalid data/i", $info)){         return false;       }$match = array();       preg_match("/\d{2,}x\d+/", $info, $match);       list($width, $height) = explode("x", $match[0]);$match = array();       preg_match("/Duration:(.*?),/", $info, $match);       if($match)       {         $duration = date("H:i:s", strtotime($match[1]));       }else       {         $duration = NULL;       }      $match = array();       preg_match("/bitrate:(.*kb\/s)/", $info, $match);       $bitrate = $match[1];if(!$width && !$height && !$duration && !$bitrate){         return false;       }else{         return array(           "file" => $file,           "width" => $width,           "height" => $height,           "duration" => $duration,           "bitrate" => $bitrate,           "secends" => $this->timeToSec($duration)         );       }     }/**   *  设置截图时间   */    private function setShootSecends($secends,$useDefault = NO)   {if($useDefault)     {       if($secends<18)       {         $time = 1;       }else       {         $time = 5;       }    $range = floor(($secends - $time)/ ($this->maxShoots));       if ($range < 1)        {         $range = 1;       }  $this->timeArray = array();       for($i=0;$i<$this->maxShoots;$i++)       {         $this->timeArray[$i] = $this->secToTime($time);         $time = $time + $range;         if ($time > $secends) break;       }     }   }      /**   *  拼接图片   */   private function getFixedPhoto($fileName)   {        $target = $this->rootdir.DS.$this->emptyImageName;//背景图片     $target_img = Imagecreatefromjpeg($target);     $source= array();      foreach ($this->fileArray as $k=>$v)     {       $source[$k]['source'] = Imagecreatefromjpeg($v);       $source[$k]['size'] = getimagesize($v);     }      $tmpx=5;     $tmpy=5;//图片之间的间距     for ($i=0; $i< count($this->timeArray); $i++)     {         imagecopy($target_img,$source[$i]['source'],$tmpx,$tmpy,0,0,$source[$i]['size'][0],$source[$i]['size'][1]);       $target_img = $this->setTimeLabel($target_img,$tmpx,$tmpy,$source[$i]['size'][0],$source[$i]['size'][1],$this->timeArray[$i]);         $tmpx = $tmpx+ $source[$i]['size'][0];       $tmpx = $tmpx+5;       if(($i+1) %3 == 0){         $tmpy = $tmpy+$source[$i]['size'][1];         $tmpy = $tmpy+5;         $tmpx=5;       }     }          $target_img = $this->setVideoInfoLabel($target_img,$tmpx,$tmpy,$this->videoInfo);     Imagejpeg($target_img,$this->rootdir.DS.$this->destination.DS.$fileName.'.jpg');    }      /**   *  设置时间刻度标签   */   private function setTimeLabel($image,$image_x,$image_y,$image_w,$image_h,$img_text)   {      imagealphablending($image,true);      //设定颜色      $color=imagecolorallocate($image,255,255,255);      $ttf_im=imagettfbbox(30 ,0,"Arial.ttf",$this->img_text);      $w = $ttf_im[2] - $ttf_im[6];       $h = $ttf_im[3] - $ttf_im[7];       unset($ttf_im);$txt_y   =$image_y+$image_h+$h-5;      $txt_x   =$image_x+$w+5; imagettftext($image,30,0,$txt_x,$txt_y,$color,"Arial.ttf",$img_text);      return $image;     }       /**   *  设置视频信息标签   */    private function setVideoInfoLabel($image,$txt_x,$txt_y,$videoInfo)    {      imagealphablending($image,true);         $color=imagecolorallocate($image,0,0,0);        imagettftext($image,32,0,100,2000+30,$color,"FZLTHJW.ttf","FileName:".basename($videoInfo["file"]));      imagettftext($image,32,0,1600,2000+30,$color,"Arial.ttf","Size:".$videoInfo["width"]."x".$videoInfo["height"]);      imagettftext($image,32,0,100,2000+120,$color,"Arial.ttf","Duration:".$videoInfo["duration"]);      imagettftext($image,32,0,1600,2000+120,$color,"Arial.ttf","Bitrate:".$videoInfo["bitrate"]);      return $image;    }       /**   *  屏幕截图   */   public function getScreenShoot($fileName)   {     $fi = pathinfo($fileName);     $this->videoInfo = $this->getVideoInfo($this->rootdir.DS.$this->source.DS.$fileName);     if($this->videoInfo)     {       $this->setShootSecends($this->videoInfo["secends"]);for ($i=0; $i< count($this->timeArray); $i++ )       {         $cmd=".".DS."ffmpeg -ss ". $this->timeArray[$i] ." -i ". $this->rootdir.DS.$this->source.DS.$fileName ." -y -f image2 -s 720*480 -vframes 1 ".$this->rootdir.DS.$this->fileArray[$i];           exec($cmd,$out,$status);         }       $this->getFixedPhoto($fileName);  $str = sprintf("[%s]:OK...........[%s][%2dP]%-30s\n",date("y-m-d h:i:s",time()),$this->videoInfo["duration"],count($this->timeArray),$fileName);       file_put_contents("log.txt",$str,FILE_APPEND);       $this->successCount += 1;     }else     {       $str = sprintf("[%s]:FAILED.................................[%s][%2dP]%-30s\n",date("y-m-d h:i:s",time()),$this->videoInfo["duration"],count($this->timeArray),$fileName);       file_put_contents("log.txt",$str,FILE_APPEND);        $this->failedCount += 1;     }   }      /**   *  TODO:   *  截取图片,   *  需要配置ffmpeg-php,比较麻烦,   *  但是这个类确实挺好用的。   */   public function getScreenShoot2($fileName)   {     if(extension_loaded('ffmpeg')){//判断ffmpeg是否载入        $mov = new ffmpeg_movie($this->rootdir.DS.$this->source.DS.$fileName);//视频的路径        $count = $mov->getFrameCount();       $ff_frame = $mov->getFrame(floor($count/2));        if($ff_frame)       {         $gd_image = $ff_frame->toGDImage();  $img=$this->rootdir.DS."test.jpg";//要生成图片的绝对路径          imagejpeg($gd_image, $img);//创建jpg图像          imagedestroy($gd_image);//销毁一图像        }     }else{        echo "ffmpeg没有载入";      }    } }  $fileLoader = new FileLoader(); $fileLoader->searchDir(); ?> 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:

  • php使用CutyCapt实现网页截图保存的方法
  • php使用ffmpeg获取视频信息并截图的实现方法
  • php实现粘贴截图并完成上传功能
  • PHP基于ffmpeg实现转换视频,截图及生成缩略图的方法
  • Linux环境下php实现给网站截图的方法
  • php通过执行CutyCapt命令实现网页截图的方法
  • php实现上传图片生成缩略图示例
  • PHP中使用FFMPEG获取视频缩略图和视频总时长实例
  • php实现根据url自动生成缩略图的方法
  • 使用PHP生成图片的缩略图的方法
  • Windows平台PHP+IECapt实现网页批量截图并创建缩略图功能详解


  • 上一条:
    PHP基于非递归算法实现先序、中序及后序遍历二叉树操作示例
    下一条:
    PHP实现统计一个数字在排序数组中出现次数的方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客