Skip to content
ELECTRONICS ENGINEERINGelectronics-engineering.com
Python

Trimming an animated GIF in Python

You can trim an animated GIF in Python with a few lines of code. Trimming means shortening it by removing frames both at the beginning and at the end from moviepy.editor import VideoFileClip # Open the file…

https://www.electronics-engineering.com/en/trimming-an-animated-gif-in-python/

Was this page useful? Rate it:
average 5.0 from 1 rating

You can trim an animated GIF in Python with a few lines of code.

Trimming means shortening it by removing frames both at the beginning and at the end

from moviepy.editor import VideoFileClip

# Apri il file GIF come video
input_file_name = 'input.gif'
output_file_name = 'trimmed.gif'

# Imposta il tempo iniziale e finale da cui iniziare e 
# terminare il ritaglio (in secondi)
tempo_iniziale_sec = 2.0  # Esempio: inizia a 2.0 secondi
tempo_finale_sec = 15.0   # Esempio: termina a 15.0 secondi

# Apri il file GIF come video utilizzando moviepy
video_clip = VideoFileClip(input_file_name)

# Esegui il taglio del video
trimmed_clip = video_clip.subclip(tempo_iniziale_sec, tempo_finale_sec)

# Salva il video ritagliato come una nuova GIF
trimmed_clip.write_gif(output_file_name)

to run these lines of code you need to install the “moviepy” library.

I consider this the most stable library because it does not change the quality of the source file, so:
it creates no problems with frame speed or flickering of the images

This code is particularly handy for reducing the file size and therefore the size of attachments for chat discussions and emails

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
1
0
Would love your thoughts, please comment.x
()
x