Creating an Animated GIF with Python

Animated GIFs are an image type that contains multiple images with slight differences. These are then played back kind of like a cartoon is. You could even think of it as a flip-book with a stick man that is slightly different on each page. When you flip the book, the image appears to move.

You can create your own animated GIFs using the Python programming language and the Pillow package.

Let’s get started!

What You Need

You will need to have Python installed on your machine. You can install it from the Python website or use Anaconda. You will also need to have Pillow. If you are using Anaconda, Pillow is already installed.

Otherwise, you will need to install Pillow. Here is how to do that using pip:

python3 -m pip install Pillow

Once Pillow is installed, you are ready to create a GIF!

Creating an Animation

You need to have multiple frames of animation to create an animated GIF. If you have a good point-and-shoot or a DSLR camera, you can usually use their high-speed settings to take a series of photos very quickly.

If you want your GIF to look nice, you should use a tripod or put your camera onto a sturdy surface before taking those photos.

You can also use Pillow to draw a series of images and turn that series into a GIF. You will learn how to use both of these methods to create an animated GIF in this article.

The first method you will learn about is how to take a series of images (JPGs) and turn them into an animated GIF. Create a new file and name it gif_maker.py. Then enter the following code:

import glob

from PIL import Image


def make_gif(frame_folder):
    frames = [Image.open(image) for image in glob.glob(f"{frame_folder}/*.JPG")]
    frame_one = frames[0]
    frame_one.save("my_awesome.gif", format="GIF", append_images=frames,
               save_all=True, duration=100, loop=0)
    

if __name__ == "__main__":
    make_gif("/path/to/images")

Here you import Python’s glob module and Pillow’s Image class. You use glob to search for JPG files in the path that you pass to your make_gif() function.

Note: You will need to pass in a real path instead of using the placeholder that is in the code above

The next step is to create a Python list of Image objects. If your images are large, you may want to add a step to resize them so that the GIF itself isn’t huge! If you don’t, you are effectively taking in all those images and turning them into one giant file. Check out How to Resize Photos with Pillow to learn more!

Once you have your Python list of images, you tell Pillow to save() it as a GIF using the first Image in your Python list. To make that happen, you need to specifically tell Pillow that the format is set to “GIF”. You also pass in your frames of animation to the append_images parameter. You must also set the save_all parameter to True.

You can set the duration of each frame in milliseconds. In this example, you set it to 100 ms. Finally, you set loop to 0 (zero), which means that you want the GIF to loop forever. If you set it to a number greater than zero, it would loop that many times and then stop.

If you’d like to test this code out on something, you can use this zip archive of hummingbird images. When you run this code against this unzipped folder, your GIF will look like this:

The reason this GIF is not very smooth is that these photos were taken without a tripod. Try taking some shots of something moving using a tripod and then re-run this code and it will be much smoother.

Now you’re ready to learn how to create an animation by drawing with Pillow!

Drawing An Animation with Pillow

Pillow lets you draw various shapes as image objects. You can use this to create your own animation! If you’d like to learn more about what kinds of drawings you can create with Pillow, then you might like this article: Drawing Shapes on Images with Python and Pillow.

For this example, you will draw circles using Pillow’s ellipse shape. You can also draw arcs, lines, rectangles, polygons, lines and more.

To get started, create a new file and add the following code:

from PIL import Image, ImageDraw

def ellipse(x, y, offset):
    image = Image.new("RGB", (400, 400), "blue")
    draw = ImageDraw.Draw(image)
    draw.ellipse((x, y, x+offset, y+offset), fill="red")
    return image


def make_gif():
    frames = []
    x = 0
    y = 0
    offset = 50
    for number in range(20):
        frames.append(ellipse(x, y, offset))
        x += 35
        y += 35
        
    frame_one = frames[0]
    frame_one.save("circle.gif", format="GIF", append_images=frames,
                   save_all=True, duration=100, loop=0)
    

if __name__ == "__main__":
    make_gif()

The code in the make_gif() function is nearly identical to the previous example. The main difference is how you build your Python list of frames. In this case, you create a loop that creates 20 images and appends them to the frames list.

To create your circles, you call the ellipse() function. It accepts the x and y position that you want to draw the ellipse at. It also includes an offset value. The offset is used to determine how large to draw the image. Pillow’s ellipse() method takes in the beginning x/y coordinate of the radius of your ellipse and the ending x/y coordinate of the radius. Then it draws the ellipse.

When the ellipse is drawn, it is added to a new image that is 400 x 400 pixels. This image has a blue background. The circle (or ellipse) has a blue background.

Go ahead and run your code. The output will look like this:

Isn’t that great? Try changing the shape that you draw. Or edit your code to use different colors. You could add more than one ball to your animation too!

Wrapping Up

You can lots more with the Pillow package. You can edit photos, apply effects,, change image contrast and so much more. Have fun learning more about Pillow and Python! It’s great.