Python Script: Convert Video MP4 to GIF (Source code download)


Welcome to this tutorial on how to convert video MP4 to GIF in Python. We will be using the moviepy library, which makes it easy to work with videos in Python. This library allows us to work with a wide range of video file formats, including MPEG, AVI, and more. In this tutorial, we will be focusing on how to use moviepy to convert a video from MP4 format to GIF format.

Converting Video MP4 to GIF

We will start by Importing the moviepy library. To do this, we will type the following code into our Python interpreter:

import moviepy
Code language: JavaScript (javascript)

Next, we will need to open our video file. We can do this by typing the following code into our Python interpreter:

clip = mp.VideoFileClip("video.mp4")
Code language: JavaScript (javascript)

Now that our video file is open, we can convert it to GIF format. To do this, we will type the following code into our Python interpreter:

clip.write_gif("video.gif")
Code language: CSS (css)

A Full Python Script to convert video MP4 to GIF

from moviepy.editor import VideoFileClip import re import argparse def video_to_gif(PATH, START_TIME, END_TIME, OUTPUT_NAME): if not START_TIME or not END_TIME: clip = VideoFileClip(PATH) else: print("Creating GIF from time %s sec to %s sec." % (str(START_TIME), str(END_TIME))) clip = VideoFileClip(PATH).subclip((START_TIME), (END_TIME)) clip.write_gif(OUTPUT_NAME) def main(): parser = argparse.ArgumentParser() parser.add_argument("path", help="Path of video file") parser.add_argument("--start", "-s", help="Start time") parser.add_argument("--end", "-e", help="End time") args = parser.parse_args() PATH = args.path START_TIME = args.start END_TIME = args.end VIDEO_EXT = re.search(r"\.([a-zA-Z0-9]{2,5}$)", PATH).group(1) OUTPUT_NAME = PATH.replace(VIDEO_EXT, "gif", 1) video_to_gif(PATH, START_TIME, END_TIME, OUTPUT_NAME) if __name__ == "__main__": main()
Code language: Python (python)

Usage

cd video_to_gif python3 video2gif.py --start --end
Code language: CSS (css)

Download the source code here.

And that’s all there is to it! You have now successfully converted a video from MP4 format to GIF format using Python.

Conclusion:

In this tutorial, we learned how to use the moviepy library to convert a video from MP4 format to GIF format in Python. We started by importing the moviepy library and then opened our video file. After that, we were able to convert our video file to GIF format by typing just a few lines of code. Thanks for reading!

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts