萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 從 FLV 影片動態擷取預覽圖 (支援時間點與百分比)

功能特色

本脚本可透過 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.png

安全與效能提醒

  1. 輸入驗證:嚴格過濾 file 參數,限制允許目錄與副檔名,防止路徑遍歷與任意檔案讀取。
  2. 指令注入防護:所有外部參數進入 exec/passthru 前,務必使用 escapeshellarg() 或 escapeshellcmd()。
  3. 快取機制:相同參數請求可快取產生的圖片,避免重複啟動 FFmpeg 造成 CPU 飆升。
  4. 非同步預生成:上傳影片時即啟動背景任務生成多張縮圖,前端直接讀取靜態圖,效能最佳。
copyright © 萬盛學電腦網 all rights reserved