Last modified: Oct 19, 2024 By Alexander Williams

Creating Animated GIFs using Python Pillow

Animated GIFs are a popular way to display a series of images as an animation. Using the Pillow library in Python, you can easily create animated GIFs by combining multiple images. In this guide, we'll show you how to use Pillow to create GIFs step by step.

Getting Started with Pillow

If you haven't installed Pillow yet, please check out our guide on Pillow: Installation and getting started (Python). Once installed, you're ready to start creating GIFs.

Combining Images to Create an Animated GIF

To create an animated GIF, you need a sequence of images that will serve as frames. Each frame is displayed in the GIF for a short duration, creating the animation effect.


from PIL import Image

# List of image file paths
images = ['frame1.png', 'frame2.png', 'frame3.png', 'frame4.png']

# Open images and store them in a list
frames = [Image.open(image) for image in images]

# Save frames as an animated GIF
frames[0].save(
    'animated.gif',
    save_all=True,
    append_images=frames[1:],
    duration=300,
    loop=0
)

In this example, the duration parameter sets the time each frame is displayed (in milliseconds). Setting loop=0 makes the GIF loop infinitely.

Resizing and Optimizing Frames

Before creating an animated GIF, you may want to resize the frames to ensure a uniform size throughout the animation. Learn more about resizing images in our guide on Resizing Images Using Python Pillow.


# Resize each frame before creating the GIF
frames = [frame.resize((500, 500)) for frame in frames]

Resizing frames can make the final GIF smaller and help with faster loading times on websites.

Adding Text to Each Frame

You might want to add text or watermarks to each frame of your GIF. For more information on adding text to images, refer to Adding Text and Watermarks to Images using Python Pillow.

Saving Optimized GIFs

To ensure your animated GIF is optimized for size, you can use Pillow's optimize feature:


# Save the GIF with optimization
frames[0].save(
    'optimized_animated.gif',
    save_all=True,
    append_images=frames[1:],
    duration=300,
    loop=0,
    optimize=True
)

Using optimize=True can help reduce the file size of the final GIF, making it more suitable for web use.

Conclusion

With Python's Pillow library, creating animated GIFs is straightforward and efficient. By combining frames, adjusting durations, and optimizing the final GIF, you can create smooth and effective animations. For more advanced techniques like applying filters, check out our guide on Image Filters and Enhancements using Python Pillow.

Start experimenting with GIF creation and bring your images to life!