Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Python to convert video to Gif

Shulou Source: shulou.com Published: 2022-06-03 07:54:59 09月20日 Update

This article will explain in detail how to use Python to convert video to Gif. Xiaobian thinks it is quite practical, so share it with you as a reference. I hope you can gain something after reading this article.

I. Foreword

Many sites offer video-to-GIF functionality, but either for a fee or with advertising

In fact, we can convert video to gif with python and a few lines of code.

2. Course 1 moviepyip install moviepy -i https://pypi.tuna.tsinghua.edu.cn/simple2. Write code from moviepy.editor import *clip = (VideoFileClip("movie.mp4")) #Path of video file to be converted to GIF clip.write_gif("movie.gif")3. conversion effect

Although the GIF image just now was only a few seconds long, it was as large as 9 megabytes! (again with resolution scaled)

If the video to be converted is tens of seconds, the file size will have to be 100 megabytes or more!

So how do we fix this?

4. GIF Great solution

In addition to setting the zoom resolution resize, we can also reduce the size by setting the fps parameter frame extraction.

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)

After setting it to 15 frames per second, the file size was only 2m, which was reduced by 4 times!

And it doesn't make much difference visually.

5. Intercept video length conversion

We can also specify the video range to convert by setting the subclip parameter:

subclip: Capture video clips from t_start to t_end in the original video

Convert video 1-2 second clips to Gif

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)5. Specify the converted image size (resolution)

The resize parameter specifies the size of the converted image

Accepted parameters are:

(width,height) in pixels or floats

Scale percentage, e.g. 0.5

example

1. Set the converted image to 600*400

clip = (VideoFileClip("movie.mp4").resize((600, 400)))

2. Original video zoom 50%

clip = (VideoFileClip("movie.mp4").resize(0.5)) About "How to use Python to convert video to Gif" This article is shared here. I hope the above content can be helpful to everyone so that you can learn more knowledge. If you think the article is good, please share it for more people to see.

Tags: Video size parameters resolution pictures files more articles code only can be passed effects clips or good practical large pixels content preface Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Redmi vpn NVidia Shulou Information