如何用脚本批量提取视频缩略图?

wen 实用脚本 2

本文目录导读:

如何用脚本批量提取视频缩略图?

  1. 方法一:使用 FFmpeg + Shell 脚本 (Linux/Mac)
  2. 方法二:Python 脚本(跨平台)
  3. 方法三:批量提取多个时间点缩略图
  4. 方法四:使用 Node.js 脚本
  5. 安装 FFmpeg
  6. 常用参数说明
  7. 进阶:带进度显示

可以使用 FFmpeg 配合脚本来批量提取视频缩略图,以下是几种常用方法:

使用 FFmpeg + Shell 脚本 (Linux/Mac)

#!/bin/bash
# 批量提取缩略图脚本
# 设置输出目录
output_dir="thumbnails"
mkdir -p "$output_dir"
# 遍历所有视频文件
for video in *.mp4 *.avi *.mov *.mkv; do
    if [ -f "$video" ]; then
        # 提取第5秒的缩略图
        ffmpeg -i "$video" -ss 00:00:05 -vframes 1 "$output_dir/${video%.*}_thumb.jpg"
        echo "已提取: $video"
    fi
done

Python 脚本(跨平台)

import os
import subprocess
from pathlib import Path
def extract_thumbnails(video_dir, output_dir="thumbnails", time_point="00:00:05"):
    """批量提取视频缩略图"""
    # 创建输出目录
    Path(output_dir).mkdir(exist_ok=True)
    # 支持的视频格式
    video_extensions = ('.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv')
    # 遍历目录
    for video_file in Path(video_dir).glob('*'):
        if video_file.suffix.lower() in video_extensions:
            output_name = f"{video_file.stem}_thumb.jpg"
            output_path = Path(output_dir) / output_name
            # FFmpeg命令
            cmd = [
                'ffmpeg',
                '-i', str(video_file),
                '-ss', time_point,
                '-vframes', '1',
                str(output_path)
            ]
            try:
                subprocess.run(cmd, check=True, capture_output=True)
                print(f"已提取: {video_file.name}")
            except subprocess.CalledProcessError as e:
                print(f"提取失败: {video_file.name} - {e.stderr.decode()}")
# 使用示例
extract_thumbnails("./videos")  # 批量处理videos文件夹下的所有视频

批量提取多个时间点缩略图

#!/bin/bash
# 提取多个时间点的缩略图
output_dir="thumbnails_multi"
mkdir -p "$output_dir"
for video in *.mp4; do
    if [ -f "$video" ]; then
        basename="${video%.*}"
        # 提取第5秒、10秒、30秒的缩略图
        for time in "00:00:05" "00:00:10" "00:00:30"; do
            time_formatted=$(echo $time | tr ':' '_')
            ffmpeg -i "$video" -ss "$time" -vframes 1 "$output_dir/${basename}_${time_formatted}.jpg"
        done
        echo "已完成: $video"
    fi
done

使用 Node.js 脚本

const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
async function extractThumbnails(videoDir, outputDir = './thumbnails') {
    if (!fs.existsSync(outputDir)) {
        fs.mkdirSync(outputDir);
    }
    const videoExts = ['.mp4', '.avi', '.mov', '.mkv'];
    const files = fs.readdirSync(videoDir);
    for (const file of files) {
        const ext = path.extname(file).toLowerCase();
        if (videoExts.includes(ext)) {
            const inputPath = path.join(videoDir, file);
            const outputPath = path.join(outputDir, `${path.basename(file, ext)}_thumb.jpg`);
            const command = `ffmpeg -i "${inputPath}" -ss 00:00:05 -vframes 1 "${outputPath}"`;
            try {
                await new Promise((resolve, reject) => {
                    exec(command, (error, stdout, stderr) => {
                        if (error) reject(error);
                        else resolve();
                    });
                });
                console.log(`已提取: ${file}`);
            } catch (error) {
                console.error(`提取失败: ${file} - ${error.message}`);
            }
        }
    }
}
// 使用
extractThumbnails('./videos');

安装 FFmpeg

如果还没有安装 FFmpeg:

  • Ubuntu/Debian: sudo apt install ffmpeg
  • Mac: brew install ffmpeg
  • Windows: 从 ffmpeg.org 下载

常用参数说明

参数 说明
-i 输入文件
-ss 起始时间(格式:HH:MM:SS)
-vframes 提取的帧数
-s 设置缩略图尺寸(如 320x240
-q:v 输出质量(2-31,数值越小质量越高)

进阶:带进度显示

#!/bin/bash
# 带进度显示的批量提取
total=$(ls *.mp4 2>/dev/null | wc -l)
count=0
for video in *.mp4; do
    count=$((count + 1))
    echo "[$count/$total] 正在处理: $video"
    ffmpeg -i "$video" -ss 00:00:05 -vframes 1 "${video%.*}_thumb.jpg" -hide_banner -loglevel error
done
echo "处理完成!"

这些脚本会自动处理整个文件夹中的视频文件,提取指定时间点的缩略图,根据您的需求调整 -ss 参数来改变提取的时间点。

抱歉,评论功能暂时关闭!