Fundamentals 4 min read

Reverse a GIF with Python: Full Tutorial and Code Samples

This tutorial shows how to reverse an existing GIF and create new GIF animations in Python using Pillow and imageio, including step‑by‑step code examples, frame extraction, reversal, and saving, plus a quick method for assembling multiple images into a GIF.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Reverse a GIF with Python: Full Tutorial and Code Samples

Recently I saw a forum question about generating GIF animations with Python. Inspired by the answers, I tried reversing a GIF by reading its frames, reversing the order, and saving a new GIF.

Below are the results:

Code example using Pillow:

<code># encoding: utf-8
from PIL import Image, ImageSequence

# Open GIF
im = Image.open("nba.gif")
# Iterate frames and save each as PNG
index = 1
for frame in ImageSequence.Iterator(im):
    print("image %d: mode %s, size %s" % (index, frame.mode, frame.size))
    frame.save("./images/frame%d.png" % index)
    index += 1

# Collect frames
imgs = [frame.copy() for frame in ImageSequence.Iterator(im)]
# Reverse frames
imgs.reverse()
# Save reversed GIF
imgs[0].save('./reverse_out.gif', save_all=True, append_images=imgs[1:])
</code>

A minimal version:

<code># encoding: utf-8
from PIL import Image, ImageSequence

im = Image.open(r'./nba.gif')
sequence = []
for f in ImageSequence.Iterator(im):
    sequence.append(f.copy())
sequence.reverse()
sequence[0].save(r'./r-nba.gif', save_all=True, append_images=sequence[1:])
</code>

Generating a GIF from multiple static images with imageio:

<code># coding=utf8
import imageio, os

path = '../images'
filenames = [os.path.join(path, f) for f in os.listdir(path)
             if f.lower().endswith(('jpg', 'jpeg', 'png'))]

images = [imageio.imread(fn) for fn in filenames]
imageio.mimsave('movie.gif', images, duration=0.3)
</code>

More flexible approach using imageio writer:

<code>import imageio

with imageio.get_writer('/path/to/movie.gif', mode='I') as writer:
    for filename in filenames:
        image = imageio.imread(filename)
        writer.append_data(image)
</code>

Using imageio is recommended over the older image2gif package.

Pythonimage processingGIFpillowimageio
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.