# 使用 Python 和 FFmpeg 修改 MP4 视频的封面图

**URL:** <https://www.isharkfly.com/t/python-ffmpeg-mp4/16085>\
**Category:** 程序语言\
**Tags:** python\
**Created:** [August 3, 2024, 10:06am UTC](https://www.isharkfly.com/t/python-ffmpeg-mp4/16085 "2024-08-03T10:06:57Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![VegaMonika](https://www.isharkfly.com/user_avatar/www.isharkfly.com/vegamonika/32/14424_2.png) [@VegaMonika](https://www.isharkfly.com/u/VegaMonika)\
**Post date:** [August 3, 2024, 10:06am UTC](https://www.isharkfly.com/t/python-ffmpeg-mp4/16085/1 "2024-08-03T10:06:57Z")

</div>

自己发资源的时候想到了然后就实践了

 ![image](https://cdn.isharkfly.com/com-isharkfly-www/discourse-uploads/original/2X/1/17eafc12a98fe18d6a6432e7e9bebf50a07be973.png)  
 ![image](https://cdn.isharkfly.com/com-isharkfly-www/discourse-uploads/original/2X/e/e38fd5813f261bf2961411cea7e0dee5f110d037.png)  
简单实用 只需要用鼠标点击既可选择

# 功能介绍

在这个教程中，我们将展示如何使用 Python 和 FFmpeg 工具将 PNG 图片设置为 MP4 视频的封面图。这个脚本将帮助你：

- 在指定目录中查找 MP4 和 PNG 文件。
- 让用户选择要更新封面图的 MP4 文件和用作封面图的 PNG 文件。
- 使用 FFmpeg 将 PNG 图片设置为 MP4 视频的封面图，并保存为新的 MP4 文件。

### 环境准备

1. **安装 Python** : 确保你已经安装了 Python如果没有，请从 [Python](https://www.python.org/downloads/) 下载并安装
2. **安装 FFmpeg** : 从 [FFmpeg](https://ffmpeg.org/download.html) 下载并安装
3. **安装 `prompt_toolkit`** : 这是一个用于创建命令行界面的 Python 库，你可以使用以下命令进行安装`pip install prompt_toolkit`

## 代码

```auto
import os
import subprocess
from prompt_toolkit.shortcuts import checkboxlist_dialog, input_dialog, message_dialog

def find_files(directory, ext):
    """在指定目录中查找特定扩展名的文件"""
    return [f for f in os.listdir(directory) if f.endswith(ext)]

def add_thumbnail_to_video(video_file, image_file, output_file):
    """将图片设置为视频的封面图"""
    command = [
        'ffmpeg', '-i', video_file, '-i', image_file, 
        '-map', '0', '-map', '1', '-c', 'copy', 
        '-disposition:v:1', 'attached_pic', output_file
    ]
    try:
        subprocess.run(command, check=True)
    except subprocess.CalledProcessError:
        pass # 错误处理已通过 UI 提供反馈

def main():
    # 显示公告
    message_dialog(
        title='公告',
        text="测试",
        ok_text='确定'
    ).run()

    # 选择工作目录
    directory = input_dialog(
        title='目录选择',
        text='请输入要操作的目录（留空表示当前目录）',
        default=os.getcwd()
    ).run() or os.getcwd()

    if not os.path.isdir(directory):
        message_dialog(
            title='错误',
            text='指定的目录不存在。',
            ok_text='确定'
        ).run()
        return

    # 查找 MP4 和 PNG 文件
    mp4_files = find_files(directory, '.mp4')
    png_files = find_files(directory, '.png')

    if not mp4_files:
        message_dialog(
            title='错误',
            text='没有找到 MP4 文件',
            ok_text='确定'
        ).run()
        return
    if not png_files:
        message_dialog(
            title='错误',
            text='没有找到 PNG 文件',
            ok_text='确定'
        ).run()
        return

    # 用户选择 MP4 文件
    selected_mp4 = checkboxlist_dialog(
        title='选择 MP4 文件',
        text='选择要更新封面图的 MP4 文件',
        values=[(f, f) for f in mp4_files] + [('取消', '取消')],
        ok_text='确定',
        cancel_text='取消'
    ).run()
    if selected_mp4 is None or '取消' in selected_mp4:
        return

    # 用户选择 PNG 文件
    selected_png = checkboxlist_dialog(
        title='选择 PNG 文件',
        text='选择要用作封面图的 PNG 文件',
        values=[(f, f) for f in png_files] + [('取消', '取消')],
        ok_text='确定',
        cancel_text='取消'
    ).run()
    if selected_png is None or '取消' in selected_png:
        return

    # 用户输入自定义文件名
    default_name = "www.justnainai.com.mp4"
    output_file_name = input_dialog(
        title='文件名输入',
        text='请输入导出视频的文件名（直接回车使用默认值）',
        default=default_name
    ).run() or default_name

    output_file = os.path.join(directory, output_file_name)

    # 添加封面图
    add_thumbnail_to_video(
        os.path.join(directory, selected_mp4), 
        os.path.join(directory, selected_png), 
        output_file
    )

if __name__ == " __main__":
    main()

```

# 使用步骤

如果不懂 可以下载我打包好的 帖子最下面.exe

cmd 启动输入Python 你的文件名字.py  
既可运行

> **[宅宅的云盘中心](https://yunpan.justnainai.com/home?path=cloudreve%3A%2F%2FlpEcq%40share)**
>
> 宅宅的云盘中心提供丰富的二次元资源，安全存储，快速下载，随时随地访问精彩内容！

 ![image](https://cdn.isharkfly.com/com-isharkfly-www/discourse-uploads/original/2X/c/cc6fcb5cfcf4fb8de78e149a3475bd02c19da53d.png)

 ![thumbnail](https://cdn.isharkfly.com/com-isharkfly-www/discourse-uploads/original/2X/d/d4a1f798232e8de79b688ac09c9df21b7bdc8226.jpeg)
