Quick and Easy Gif Creation and Optimization with Python

Jonathan Joyner
The Dev Project
Published in
5 min readJun 6, 2022

Generating gifs with python can be a pain and there is not much information out there on how it’s done.

In addition, there is no comprehensive Python library that I could find for optimizing gifs programmatically.

I did end up figuring out an efficient solution to making gifs programmatically in Python after hours of research and have distilled it into just the necessities. In this process, we’ll use two tools: the Pillow library and Gifsicle.

The Pillow library allows us to manipulate images in various ways and Gifsicle is a CLI tool used for gif manipulation. So let’s dive into how to edit gifs with Python.

Using Pillow

For this example, I’ll take this gif:

Gif

And put this hat on him:

Hat

To start, we need to install Pillow:

pip install Pillow

and we also need to import the Image class from Pillow:

from PIL import Image

Now, we’ll want to get our images as Image objects. We can run the code below (with your own file path) to show the images and make sure everything is working:

Show Images

The gif will only show the first frame, that’s normal. If nothing shows up, check your import statement and file path.

For now, we’ll work with just the first frame of the gif and swap over to the full gif once we have everything looking good on the first frame.

Because my hat image has a transparent background, I use the mask argument. If your image doesn’t skip that part.

And here’s what we get:

Hat Pasted

As you can see, the hat color isn’t correct but that’s okay! That will fix itself later.

Now that we have our images together. We just need to position the hat. We can do this by altering the arguments in the paste method:

gif.paste(hat, (375, -55), mask = hat)

Here I’ve added the amount of offset in the x and y directions as a tuple. The hat image will be offset by 375px on the x-axis and -55px (going up instead of down) in the y-axis.

Now we are set up on our images:

Hat Positioned

Now we just need to paste the hat in this position over each frame of the gif. We do this by importing the ImageSequence object from PIL and using it to grab all of the frames:

from PIL import Image, ImageSequence

In the code below, I copy each from the iterator which iterates over the gif frames. From there, I paste the hat on the frame and append that frame to the list of created frames.

Generating All Gif Frames

Once the frames are made, we have to save the file to view the new gif:

new_gif[1].save(
'gif_creation/new_gif.gif',
save all = True,
appen_images = new_gift[1:],
loop = 0
)

This method saves the first frame and appends all other frames of the gif. The loop argument allows us to either set a number of loops or use 0 for infinite loops.

Once saved we have a new gif:

And now for the full code:

Gif Creation Code

Not too bad. At this point, the gifs could be generated and used as needed.

However, in my personal project, I was creating very large gifs which could not be uploaded to image hosting platforms.

Optimizing the Gif

So I had to go one step further and optimize the gifs. There are not many good options in Python for gif optimization. There is one excellent CLI tool that does just that called Gifsicle.

If you’re not familiar, CLI (command-line interface) tools are used in the command line. One example of a CLI tool would be Git.

In order to use Gifsicle, you’ll need to download it. All the download links can be found here.

Once downloaded, it’s extremely easy for us to run gifsicle commands in Python. We can simply run a subprocess with all of the items in the command line as a list.

For this particular example, we’ll reduce the size of the gif through lossy compression and limit the number of colors used. There are many other ways Gifsicle can be used to optimize gifs, ezgif.com uses it and shows some great examples of all the possibilities with the tool.

The following code runs optimization after the gif creation:

Optimized Gif Creation

And we get out this gif:

As you can see, it has been compressed. The overall size of the gif dropped from 8.3MB to 3.1MB.

Conclusion

This is the basics of gif generation and optimization with Python. There is much more that can be done using just the methods shown in this example.

Creating gifs over other gifs and even moving the hat from frame to frame is relatively easy to do which allows for pretty much any type of gif generation.

Hopefully, this has saved you some time reading docs on these tools and gives you a head start on your gif generation journey.

If this helped you out, consider following me on twitter or here on Medium.

Sign up for our Free Weekly Newsletter. Fresh content from developers all over the world, fresh and direct from the field! Don’t forget to follow our publication The Dev Project.

--

--