本脚本可透過 URL 參數動態從 FLV (或其他 FFmpeg 支援格式) 影片擷取預覽圖,支援:
time=00:00:05)percent=75.3,自動換算時間)browser=true) 或儲存檔案 (browser=false)<?php
// 參數接收與預設值
$videofile = isset($_GET['file']) ? strval($_GET['file']) : 'video.flv';
$imageBase = substr($videofile, 0, strlen($videofile) - 4);
$time = isset($_GET['time']) ? strval($_GET['time']) : '00:00:01';
// 時間格式簡易驗證
if (!preg_match('/^\d{2}:\d{2}:\d{2}$/', $time)) {
$time = '00:00:00';
}
// 百分比模式:先用 ffmpeg 取得總長度,再換算時間
if (isset($_GET['percent'])) {
$percent = floatval($_GET['percent']);
ob_start();
exec(escapeshellcmd("/usr/bin/ffmpeg -i " . $videofile . " 2>&1"));
$durationOutput = ob_get_clean();
if (preg_match('/Duration: (.*?),/', $durationOutput, $matches)) {
$duration = $matches[1]; // HH:MM:SS.xx
$parts = explode(':', $duration);
$totalSec = $parts[0]*3600 + $parts[1]*60 + floatval($parts[2]);
$targetSec = $totalSec * $percent / 100;
$h = intval($targetSec / 3600);
$m = intval(($targetSec % 3600) / 60);
$s = $targetSec - $h*3600 - $m*60;
$time = sprintf('%02d:%02d:%06.3f', $h, $m, $s);
}
}
$browser = isset($_GET['browser']) ? strval($_GET['browser']) : 'true';
if ($browser === 'true') {
// 直接輸出 PNG 圖片串流
header('Content-Type: image/png');
$cmd = sprintf(
'/usr/bin/ffmpeg -vcodec png -i %s -ss %s -vframes 1 -f image2 -',
escapeshellarg($videofile),
escapeshellarg($time)
);
passthru($cmd);
} else {
// 儲存為檔案
$cmd = sprintf(
'/usr/bin/ffmpeg -vcodec png -i %s -ss %s -vframes 1 -f image2 %s%%d.png',
escapeshellarg($videofile),
escapeshellarg($time),
escapeshellarg($imageBase)
);
exec($cmd);
}
?>
ffmpeg_image.php?file=video.flv&time=00:00:10&browser=true → 直接顯示第 10 秒畫面ffmpeg_image.php?file=video.flv&percent=50&browser=false → 將 50% 處畫面存為 video001.pngfile 參數,限制允許目錄與副檔名,防止路徑遍歷與任意檔案讀取。exec/passthru 前,務必使用 escapeshellarg() 或 escapeshellcmd()。