Convert Videos to GIFs with Python in Just a Few Lines
This tutorial shows how to use Python's moviepy library to transform video files into GIFs, covering installation, basic conversion, size reduction techniques via resolution scaling and frame‑rate adjustment, as well as extracting video segments and specifying output dimensions.
1. Introduction
Many websites offer video‑to‑GIF conversion but often charge or display ads; with a few lines of Python you can perform the conversion yourself.
2. Tutorial
1. Install the required library
pip install moviepy -i https://pypi.tuna.tsinghua.edu.cn/simple2. Write the code
from moviepy.editor import *
clip = VideoFileClip("movie.mp4") # path to source video
clip.write_gif("movie.gif")3. Conversion result
The GIF above is only a few seconds long but its size is 9 MB even after resolution scaling.
If the source video is tens of seconds long, the resulting file can reach hundreds of megabytes.
4. Reducing large GIF size
Besides resizing the resolution, you can lower the frame rate (fps) to shrink the file.
from moviepy.editor import *
clip = VideoFileClip("movie.mp4").resize((488, 225))
clip.write_gif("movie.gif", fps=15) # 15 frames per secondSetting the fps to 15 reduces the file to about 2 MB, roughly a four‑fold reduction, with little visual difference.
5. Converting a video segment
Use the subclip parameter to specify the start and end times of the segment you want to convert.
from moviepy.editor import *
clip = VideoFileClip("movie.mp4").subclip(t_start=1, t_end=2).resize((488, 225))
clip.write_gif("movie.gif", fps=15)6. Specifying output resolution
The resize argument can define the output size in pixels, a scaling factor, or a percentage.
(width, height) in pixels, e.g., (600, 400) Scaling factor, e.g., 0.5 for 50 % reduction
# Set output size to 600×400
clip = VideoFileClip("movie.mp4").resize((600, 400))
# Scale original video to 50 %
clip = VideoFileClip("movie.mp4").resize(0.5)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
