一、使用方法
- mp4文件夹下放待转换的MP4,转换后生成同名的GIF文件在gif文件夹下
- 其他详细参数见代码
- 目录结构如下
根目录
|-----gif
| |
| |-----1.gif
| |-----2.gif
| |-----...
|
|-----mp4
| |
| |-----1.mp4
| |-----2.mp4
| |-----...
|
|-----start.py
二、实现
- 安装依赖
pip install moviepy
- 创建执行文件 start.py
from moviepy.editor import *
import os
class Mp42GifOp(object):
def __init__(self,
resize=None,
fps=None,
clip=None
):
self.resize = resize
self.fps = fps
self.clip = clip
def mp42gif(self, mp4path, gifpath):
vfc = VideoFileClip(mp4path)
if self.clip:
vfc = vfc.subclip(*self.clip)
if self.resize:
vfc = vfc.resize(self.resize)
clip = (vfc)
if self.fps:
clip.write_gif(gifpath, fps=self.fps)
else:
clip.write_gif(gifpath)
print("{} to {} complete!".format(mp4path, gifpath))
if __name__ == '__main__':
resize = None
fps = 9
clip = None
mp4_dir = './mp4'
gif_dir = './gif'
m2g = Mp42GifOp(resize, fps, clip)
mp4_path_list = [os.path.join(mp4_dir, file) for file in os.listdir(mp4_dir)]
for idx, mp4_path in enumerate(mp4_path_list):
print("---- 当前进度:{} / {},当前转换文件:{} ----".format(idx+1, len(mp4_path_list), mp4_path))
gifname = mp4_path.replace('\\', '/').rsplit('/', 1)[1].rsplit('.', 1)[0]
gif_path = os.path.join(gif_dir, '{}.{}'.format(gifname, 'gif'))
m2g.mp42gif(mp4_path, gif_path)