首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 使用 FFmpeg 擷取影片預覽圖(縮圖):完整指令與非同步架構

     編輯:PHP 相關知識

前言

擷取影片特定時間點的畫面作為預覽圖是影音平台核心功能。FFmpeg 的 -ss (seek) 與 -vframes 1 可高效產出單張圖片。本文示範同步呼叫與生產級非同步架構。

基本同步擷取

<?php
function extractThumbnail(string $input, string $output, string $time = '00:00:05'): bool {
    if (!file_exists($input)) {
        throw new \InvalidArgumentException("影片不存在: $input");
    }

    // -ss 00:00:05  跳至 5 秒
    // -vframes 1    只擷取 1 幀
    // -vcodec mjpeg 輸出 JPEG
    // -f rawvideo   強制 raw video 格式(舊版相容)
    // -s 286x160    縮放尺寸
    // -aspect 16:9  保持比例
    $cmd = sprintf(
        'ffmpeg -v 0 -y -i %s -vframes 1 -ss %s -vcodec mjpeg -f rawvideo -s 286x160 -aspect 16:9 %s',
        escapeshellarg($input),
        escapeshellarg($time),
        escapeshellarg($output)
    );

    shell_exec($cmd);
    return file_exists($output) && filesize($output) > 0;
}

// 使用
extractThumbnail('video.mp4', 'thumb.jpg', '00:00:10');
?>

進階:百分比定位擷取(需先取得影片長度)

<?php
function extractThumbnailAtPercent(string $input, string $output, float $percent): bool {
    // 1. 取得影片長度 (秒)
    $cmd = sprintf('ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 %s', escapeshellarg($input));
    $duration = (float) trim(shell_exec($cmd));
    if ($duration <= 0) return false;

    $seekTime = $duration * $percent / 100;
    $timeStr = gmdate('H:i:s', $seekTime); // 格式化為 HH:MM:SS

    return extractThumbnail($input, $output, $timeStr);
}
?>

直接輸出圖片串流(不落地儲存)

<?php
// 適用於  
$video = $_GET['video'] ?? '';
$time  = $_GET['time'] ?? '00:00:01';

if ($video && file_exists($video)) {
    header('Content-Type: image/jpeg');
    $cmd = sprintf(
        'ffmpeg -v 0 -y -i %s -ss %s -vframes 1 -vcodec mjpeg -f image2pipe -',
        escapeshellarg($video),
        escapeshellarg($time)
    );
    // 直接輸出 stdout
    passthru($cmd);
    exit;
}
http_response_code(404);
?>

非同步佇列架構(生產環境必備)

同步 shell_exec 會阻塞 PHP-FPM 進程,高併發下導致服務不可用。標準架構:

  1. 上傳完成 → 寫入 thumbnail_jobs 表/Redis Queue(video_path, time_points[])。
  2. Worker (Supervisor/Gearman/RoadRunner) 消費任務 → 呼叫 FFmpeg → 存入儲存 → 更新資料庫狀態。
  3. 前端輪詢/WebSocket 獲取縮圖 URL。

總結

FFmpeg 擷取縮圖指令簡潔高效,關鍵在於 -ss 定位與 -vframes 1。生產環境禁止同步呼叫,必須採用非同步佇列解耦。希望本文對您的 PHP 程式設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved