Convert Video to Gif with 3 Lines of Code in Python

Convert Video to Gif with 3 Lines of Code in Python

Easily convert a video to a GIF using Tkinter and Moviepy.

To create a video to gif converter, this is all the code you need:

from moviepy.editor import VideoFileClip
from tkinter.filedialog import *

video_file = askopenfilename()
clip = VideoFileClip(video_file)
clip.write_gif("ouput.gif", fps=10)

Detailed Steps

  1. Make sure you have MoviePy and Tkinter installed. Install MoviePy with:
    pip install moviepy
    
    If you’re running Python2, Tkinter should be built-in, so you don’t need to install it. If you’re running Python3, you should install Tkinter with:
    brew install python-tk
    
  2. Create a new Python file, e.g. gif_converter.py
  3. Copy-paste the above code to the file
  4. Run the program (in Terminal just run python gif_converter.py)
  5. Select a video you want to convert.
  6. When the conversion finishes, find the output.gif file from the same folder with the converter program.
  7. Enjoy!

Further Improvements

The above code works fine. But now you can select any type of file to be converted, which is bad. Let’s change that by restricting to only .mov and .mp4 files . Also, with the current implementation, the output GIF is always named output.gif. Let’s also change it such that the name doesn't change: example_video.mp4example_video.gif.

Here is the improved code with some helpful comments:

from moviepy.editor import VideoFileClip
from tkinter.filedialog import *
import os

# Accept only .mov and .mp4 files. Feel free to change.
accepted_files = [("Mov files", "*.mov"), ("MP4 files", "*.mp4")]

# Select a video which is one of the accepted file types from your machine
video_file = askopenfilename(filetypes=accepted_files)

# Create a video clip instance
clip = VideoFileClip(video_file)

# Get the video file name. E.g. 'path/to/video.mov' --> 'video.mov'
video_file_name = os.path.basename(video_file)

# Split video name to parts. E.g. 'video.mov' --> ('video', 'mov')
parts = os.path.splitext(video_file_name)

# Get the name of the video from the parts and add a .gif to the end.
gif_name = parts[0] + ".gif"

# Create a gif with the same name as the original video.
clip.write_gif(gif_name, fps=10)

Conclusion

Thanks for reading. I hope you find it useful!