北京赛车 pk10开奖记录_Toyou热购彩票官网
建站專提News

PHP調用ffmpeg對視頻截圖並拼接腳本

一佰互聯網站開發設計(www.yinxi.net) 發布日期 2019-04-25 14:40:46 瀏覽數: 59

PHP腳本調用ffmpeg對視頻截圖並拼接慶肪,供大家參考吩柔,具體內容如下

目前支持MKV魂豆斡,MPG吵,MP4等常見格式的視頻咳,其他格式有待測試

1热购彩票 問︰“家庭住址?”花錢花在刀口上2P 一張截圖平均生成時間  1.64s     100個視頻,大概需要2分半左右

9P  一張截圖平均生成時間  1.13s      100個視頻,大概需要2分鐘左右

6P  一張截圖平均生成時間  0.86s      1热购彩票 “你的杰作唄1吞噬我吧。00個視頻,大概需要1分半左右

3P  一張截圖平均生成時間  热购彩票 她叫馮笑霞。井河︰飽了,太飽了。0.54s      100個視頻,大概需要1分鐘左右

<?php define("DS", DIRECTORY_SEPARATOR); date_default_timezone_set("Asia/Shanghai"); class FileLoader {   //路徑變量   private $rootdir    = "";   private $tmp      = "tmp";      //tmp 目錄   private $source     = "mpg";      //source 目錄   private $destination  = "screenshoot";  //目標截圖路徑   private $emptyImageName = "empty.jpg";   //合成的背景圖   //文件數組    private $maxShoots   = 12;        //最大的截圖數   private $videoInfo   = NULL;   private $files     = array();     //文件數   private $fileArray   = array();        private $extensionArray = array("mpg","mkv","mp4","avi","3gp","mov");  //支持的格式   private $timeArray   = array("00:00:10","00:00:20","00:00:30","00:01:00","00:01:30","00:02:00","00:02:30","00:03:00","00:03:30","00:03:40","00:03:50","00:04:00");   //統計變量   private $timeStart   = 0;   private $timeEnd    = 0;   private $fileCount   = 0;   private $successCount  = 0;   private $failedCount  = 0;      /**   *  初始化信息   */     function __construct()   {     file_put_contents("log.txt","");     $this->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",$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",$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("", $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,}xd+/", $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",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",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開發和域名注冊及虛擬主機服務經驗啼遁,提供的自助建站服務更是全國有名京琳。近年來還整合團隊優勢自主開發了可視化多用戶”巔雲建站系統“3.0平台版富卜賠,拖拽排版網站制作設計創譬,輕松實現pc站撮、手機微網站帕、小程序監、APP一體化全網營銷網站建設 唐,已成功的為全國上百家網絡公司提供自助建站平台搭建服務礁浩擻。

相關新聞more

24
04月
CSS設置列表樣式和創建導航菜單實現代碼

一吭、設置列表的符號list-style-type: 屬性;//設置列表樣式list-style-type: none; //清楚樣式屬性有很... >>詳情

27
04月
php resizeimage 部分jpg文

今天遇到GD的resizeimage 函數處理jpg後綴文件的縮略圖的時候 提示該圖片不是合法的jpg圖片並報錯<b>Warni... >>詳情

28
04月
PHP中大于2038年時間戳的問題處理方案

PHP有效的時間戳典型範圍是格林威治時間 1901 年 12 月 13 日 20:45:54 到 2038 年 1 月 19 日 03:14... >>詳情

28
04月
php實現簡單文件下載的方法

本文實例講述了php實現簡單文件下載的方法硼。分享給大家供大家參考犬巒。具體如下涎闌︰這里介紹的php文件下載代碼場,只是簡單實現了一張圖片的下載功能般,... >>詳情

高端網站建設

美工兼顧SEO寬乏孩,為企業電子商務營銷助力!

電話查舷榮︰

023-85725751
建站

產品

域名注冊 虛擬主機 雲服務器 企業郵局
智能建站 APP打包 微站/小程序 創業平台
網站推廣 媒體營銷 智能采集 AI機器人
400電話 短信營銷 店銷機器人
私人定制 門戶網站
pk10 pk10开奖记录 pk10开奖