
Python写的,一个很简单的小工具,闲来无事做了一个玩玩。
代码部分:
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from moviepy.editor import VideoFileClip
import threading
import os
def video_to_gif(input_video_path, output_gif_path, start_time=None, end_time=None, progress_var=None):
"""
将视频转换为GIF。
参数:
- input_video_path: 输入视频文件路径
- output_gif_path: 输出GIF文件路径
- start_time: GIF的开始时间(以秒为单位),默认为视频开头
- end_time: GIF的结束时间(以秒为单位),默认为视频结尾
- progress_var: 用于显示进度的 tk.IntVar 对象
"""
try:
# 加载视频文件
video_clip = VideoFileClip(input_video_path)
# 裁剪视频到指定时间段
if start_time is not None and end_time is not None:
video_clip = video_clip.subclip(start_time, end_time)
# 将视频转换为GIF并保存
video_clip.write_gif(output_gif_path)
# 更新进度为100%
if progress_var:
progress_var.set(100)
messagebox.showinfo("完成", f"GIF已成功保存为 {output_gif_path}")
except Exception as e:
messagebox.showerror("错误", f"转换过程中出现错误: {e}")
def convert_to_gif(files):
start = start_time.get()
end = end_time.get()
try:
start = float(start) if start else None
end = float(end) if end else None
except ValueError:
messagebox.showerror("错误", "请输入有效的起始和结束时间。")
return
# 为每个文件创建线程
for file_path in files:
output_path = os.path.splitext(file_path)[0] + ".gif"
# 创建一个进度条
progress_var = tk.IntVar()
progress_bar = ttk.Progressbar(root, orient="horizontal", length=300, mode="determinate", variable=progress_var)
progress_bar.pack(pady=5)
progress_bar_label = tk.Label(root, text=f"转换中: {os.path.basename(file_path)}")
progress_bar_label.pack()
# 启动转换线程
conversion_thread = threading.Thread(target=video_to_gif, args=(file_path, output_path, start, end, progress_var))
conversion_thread.start()
def select_files():
file_paths = filedialog.askopenfilenames(filetypes=[("Video files", "*.mp4;*.avi;*.mov;*.mkv")])
if file_paths:
# 将选中的文件路径显示在上方框内
file_list.set('\n'.join(file_paths))
convert_button.config(state=tk.NORMAL)
# 创建主窗口
root = tk.Tk()
root.title("批量视频转GIF工具")
root.geometry("600x400")
# 视频路径显示
file_list = tk.StringVar()
video_label = tk.Label(root, textvariable=file_list, width=60, height=4, relief="sunken", anchor="w", justify="left")
video_label.pack(pady=10)
# 文件选择按钮
select_button = tk.Button(root, text="选择文件", command=select_files)
select_button.pack(pady=10)
# 起始时间输入
tk.Label(root, text="起始时间 (秒):").pack()
start_time = tk.Entry(root)
start_time.pack(pady=5)
# 结束时间输入
tk.Label(root, text="结束时间 (秒):").pack()
end_time = tk.Entry(root)
end_time.pack(pady=5)
# 转换按钮
convert_button = tk.Button(root, text="批量转换为GIF", command=lambda: convert_to_gif(file_list.get().split('\n')))
convert_button.pack(pady=20)
convert_button.config(state=tk.DISABLED)
# 运行主循环
root.mainloop()
写了一个简单的窗口应用,支持打包成exe软件。
- All rights reserved.
- No part of this website, including text and images, may be reproduced, modified, distributed, or transmitted in any form or by any means, without the prior written permission of the author.
- Unauthorized commercial use is strictly prohibited.
- Unauthorized personal use is strictly prohibited.