ffmpegで数秒ごとに画像を切り抜いてGIFアニメーション化

ffmpegで数秒ごとに画像を切り抜いてGIFアニメーション化します。

<?php
//作業ディレクトの設定
$workpath = "/home/yourname";
//ffmpegで動画情報をPHPへ出力
$cmd_2 = "ffmpeg -i {$workpath}/move.mp4 2>&1 ";
exec( $cmd_2 , $output);
//出力結果を調査(Duration=秒数)
foreach( $output as $value ){
    $tmp = split( ":" , $value );
    if( trim( $tmp[0] )  == "Duration" ){
        $duration = $value;
    }
}
$param = split( "," ,$duration );
$param[0] = trim( $param[0] );
$time["h"] = intval( substr( $param[0] , 10,2 ) );
$time["m"] = intval( substr( $param[0] , 13,2 ) );
$time["s"] = intval( substr( $param[0] , 16,2 ) );
//総秒数を取得
$seconds = $time["h"] * 60 * 60 + $time["m"]* 60 + $time["s"];
//3秒ごとに動画から画像を切り出す
$step = 3;
for( $i = 1 ; $i * $step < $seconds ; $i ++ ){
    $s = $i * $step;
    $cmd_2 = "ffmpeg -i {$workpath}/movie.mp4 -an -ss {$s} -s 240x180 -vframes 1 {$workpath}/{$i}.png";
    system( $cmd_2 );
}
?>

png画像からgifアニメーションを作る

<?php
$cmd_3 = "convert -loop 0 -delay 100 {$workpath}/*.png {$workpath}/out.gif";
?>

ちなみに、Youtubeの動画のダウンロードはLinux系OSになりますが、youtube-dlなどが便利です。