优化使用 Flask 构建视频转 GIF 工具

优化使用 Flask 构建视频转 GIF 工具

优化后的项目概述

在优化后的版本中,我们将实现以下功能:

  1. 可设置每个 GIF 的帧率和大小:用户可以选择 GIF 的帧率和输出大小。
  2. 改进的用户界面:使用更现代的设计使界面更美观、整洁。
  3. 自定义生成的 GIF 文件名:用户可以为每个视频设置开始时间和持续时间。

优化后的项目结构

复制代码
your_project/
│
├── app_plus.py           # 优化后的 Flask 应用
├── input_videos/         # 上传视频的文件夹
├── output_gifs/          # 输出 GIF 的文件夹
└── templates/
    └── index_plus.html   # 优化后的 HTML 前端页面

Flask 应用代码 (app_plus.py)

python 复制代码
	from flask import Flask, request, render_template, redirect, url_for, send_from_directory
import subprocess
import os

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = './input_videos/'
app.config['OUTPUT_FOLDER'] = './output_gifs/'

# 确保上传和输出文件夹存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs(app.config['OUTPUT_FOLDER'], exist_ok=True)

def convert_video_to_gif(input_video_path, output_gif_path, start_time, duration, fps, scale):
    command = [
        'ffmpeg',
        '-ss', str(start_time),
        '-t', str(duration),
        '-i', input_video_path,
        '-vf', f'fps={fps},scale={scale}:-1:flags=lanczos',
        '-c:v', 'gif',
        output_gif_path
    ]
    subprocess.run(command)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        video_files = request.files.getlist('video_files')
        start_times = request.form.getlist('start_times')
        durations = request.form.getlist('durations')
        fps = request.form['fps']
        scale = request.form['scale']
        custom_name = request.form['custom_name']  # 获取自定义文件名

        for index, video_file in enumerate(video_files):
            if video_file:
                input_video_path = os.path.join(app.config['UPLOAD_FOLDER'], video_file.filename)
                # 使用用户提供的自定义文件名生成 GIF 文件
                output_gif_path = os.path.join(app.config['OUTPUT_FOLDER'], f"{custom_name}_{index}.gif")
                video_file.save(input_video_path)
                convert_video_to_gif(input_video_path, output_gif_path, start_times[index], durations[index], fps, scale)

        return redirect(url_for('index'))  # 重定向回主页

    return render_template('index_plus.html')

@app.route('/output_gifs/<filename>')
def send_gif(filename):
    return send_from_directory(app.config['OUTPUT_FOLDER'], filename)

if __name__ == '__main__':
    app.run(debug=True)

HTML 页面代码 (index_plus.html)

html 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频转GIF工具</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f0f0f0;
            color: #333;
        }
        .container {
            max-width: 800px;
            margin: 50px auto;
            padding: 30px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        h1 {
            color: #4CAF50;
            margin-bottom: 20px;
        }
        input[type="file"], input[type="number"], input[type="text"] {
            margin: 10px 0;
            padding: 15px;
            width: calc(100% - 30px);
            border: 1px solid #ccc;
            border-radius: 5px;
            transition: border-color 0.3s;
        }
        input[type="file"]:hover, input[type="number"]:hover, input[type="text"]:hover {
            border-color: #4CAF50;
        }
        button {
            margin: 20px 0;
            padding: 15px;
            width: 100%;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #45a049;
        }
        footer {
            margin-top: 30px;
            font-size: 14px;
            color: #777;
        }
        .video-input {
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 10px;
        }
        .video-input div {
            margin-bottom: 10px;
        }
        @media (max-width: 600px) {
            .container {
                padding: 20px;
            }
            h1 {
                font-size: 24px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>视频转GIF工具</h1>
        <form action="/" method="post" enctype="multipart/form-data">
            <div class="video-input">
                <input type="file" name="video_files" accept="video/*" multiple required>
                <input type="number" name="start_times" placeholder="开始时间(秒)" required>
                <input type="number" name="durations" placeholder="持续时间(秒)" required>
            </div>
            <label for="fps">帧率 (fps):</label>
            <input type="number" name="fps" placeholder="例如: 10" required>

            <label for="scale">输出大小 (宽度):</label>
            <input type="text" name="scale" placeholder="例如: 320" required>

            <label for="custom_name">自定义文件名:</label>
            <input type="text" name="custom_name" placeholder="例如: my_gif" required>

            <button type="submit">转换为 GIF</button>
        </form>
        <footer>
            <p>© 2025 无限大</p>
        </footer>
    </div>
</body>
</html>

说明

  1. Flask 应用 (app_plus.py)

    • 设置上传和输出文件夹。
    • 提供一个函数 convert_video_to_gif,用来调用 FFmpeg 生成 GIF 文件。
    • / 路由中处理文件上传和 GIF 生成。
    • 获取用户输入的自定义 GIF 文件名,生成的文件名为 自定义名字 + 索引 + .gif 以避免重名问题。
  2. HTML 界面 (index_plus.html)

    • 创建一个用户输入界面,允许用户上传视频、设置时间参数、帧率和输出大小。
    • 添加输入框让用户输入自定义 GIF 文件名。

依赖

确保安装了 Flask 和 FFmpeg:

bash 复制代码
pip install Flask

并确保 FFmpeg 已正确安装并在系统路径中。

启动和测试

运行 Flask 应用:

bash 复制代码
python app_plus.py

在浏览器中访问 http://127.0.0.1:5000/ 测试功能。

相关推荐
美狐美颜sdk6 分钟前
直播APP开发如何实现美颜功能?视频美颜SDK接入流程与技术方案解析
大数据·人工智能·音视频·美颜sdk·美颜api
数据狐(Datafox)21 分钟前
京东商品列表API技术解析与落地应用(含标准 JSON 示例)
java·大数据·前端·人工智能·python·数据分析·json
量化吞吐机27 分钟前
2026年下半年手工交易规则走向量化表达,产品该先接住哪一步
人工智能·python
Metaphor6921 小时前
使用 Python 读取和删除 Excel 文件属性
python·excel
迷迭香yy2 小时前
Python构建转融券多空识别系统从接口到因子的全流程 IG50免费开源股票数据API接口
开发语言·python·开源
月光船幽幽2 小时前
真实即粗糙,光滑是伪造
人工智能·python
一次旅行3 小时前
Attention机制从数学到工程:拆解缩放点积+多头注意力|附可运行PyTorch实现与踩坑指南
人工智能·pytorch·python
泡干脆面就番茄3 小时前
NumPy 科学计算完全指南:从数组创建到广播机制
python·numpy
denggun123453 小时前
信号量(DispatchSemaphore vs AsyncSemaphore)、swift协作式线程池 and python信号量
开发语言·python·swift
起光3 小时前
Python类与对象(一)
python