PHP调用ffmpeg对视频截图并拼接脚本
发布人:shili8
发布时间:2022-12-12 18:46
阅读次数:26
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分钟左右
< 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\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();
>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

