Introduction:
In our daily life, we often encounter the need to convert MP4 files to GIF files. For example, we want to save highlights from a video as a GIF file to share on social media. Or maybe we want to turn a video into a GIF for use on a website or app.
Traditionally, we can use some professional video editing software to convert MP4 to GIF. However, these software are often expensive and complex to operate.
Today, we will introduce a method to implement MP4 to GIF program using Python. This method is easy to learn and completely free.
C:\pythoncode\new\mp4togif
Code description:
We first need to import the wxPython, os and moviepy libraries.
Python
import wx
import os
from moviepy.editor import VideoFileClip
Then, we define a MyFrame class, which inherits from the wx.Frame class. The constructor of the MyFrame class creates a window and adds a file selection button and a conversion button to the window.
Python
class MyFrame(wx.Frame):
def __init__(self, parent, title):
super(MyFrame, self).__init__(parent, title=title, size=(400, 200))
panel = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
# 创建文件选择按钮
file_picker = wx.FilePickerCtrl(panel, message="选择MP4文件", wildcard="MP4 files (*.mp4)|*.mp4",
style=wx.FLP_USE_TEXTCTRL | wx.FLP_OPEN | wx.FLP_FILE_MUST_EXIST)
vbox.Add(file_picker, proportion=0, flag=wx.ALL | wx.EXPAND, border=10)
# 创建转换按钮
convert_btn = wx.Button(panel, label="转换为GIF")
vbox.Add(convert_btn, proportion=0, flag=wx.ALL | wx.CENTER, border=10)
# 绑定按钮事件
convert_btn.Bind(wx.EVT_BUTTON, lambda event: self.on_convert(file_picker.GetPath()))
panel.SetSizer(vbox)
self.Show()
The convert button's event handler gets the path to the file selection button. If the path is empty, an error message will pop up. If path is not empty, the path to the output GIF file is created. The program then loads the MP4 file using the moviepy library. Finally, the program saves the video as a GIF file.
Python
def on_convert(self, mp4_file):
if not mp4_file:
wx.MessageBox("请选择一个MP4文件!", "错误", wx.OK | wx.ICON_ERROR)
return
# 创建输出GIF文件路径
mp4_dir = os.path.dirname(mp4_file)
mp4_name = os.path.basename(mp4_file)
gif_file = os.path.join(mp4_dir, os.path.splitext(mp4_name)[0] + ".gif")
try:
# 使用moviepy库加载MP4文件
video = VideoFileClip(mp4_file)
# 将视频保存为GIF文件
video.write_gif(gif_file, fps=10)
wx.MessageBox("转换完成!", "提示", wx.OK | wx.ICON_INFORMATION)
except Exception as e:
wx.MessageBox(str(e), "错误", wx.OK | wx.ICON_ERROR)
result: