How to Reverse a GIF Using Python's Pillow (PIL) Library
This tutorial demonstrates how to use Python's Pillow library to decompose a GIF into individual frames, reverse their order, and reassemble them into a new reversed‑play GIF, providing step‑by‑step code and explanations for each stage.
GIF images are ubiquitous in online communication, and reversing a GIF can create a fun visual effect. This guide shows how to achieve GIF reversal using Python's Pillow (PIL) library.
1. Import the required modules
<code>from PIL import Image, ImageSequence # import Image and ImageSequence modules
im = Image.open(r'./1.gif') # place the source GIF in the same directory as the script</code>2. Decompose the GIF into individual frames
<code>sequence = [] # list to store frames
i = 0
for f in ImageSequence.Iterator(im): # iterate over each frame
sequence.append(f.copy())
i += 1
f.save('out_' + str(i) + '.png') # save each extracted frame as a PNG file</code>3. Reverse the order of the frame sequence
<code>sequence.reverse()</code>4. Reassemble the reversed frames into a new GIF
<code>sequence[0].save(r'./out_zr640.gif', save_all=True, append_images=sequence[1:]) # save the reversed GIF in the current directory</code>The resulting GIF plays the original animation backward, as shown in the example images.
- END -
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.