How to Create Animated Gifs with Python

out.gif

Have you wondered how you can make your own gifs?

Now, certainly, this is not the easiest way, but it is a fun project for learning, and heck, it might come in useful one day ;)

You may remember that I already covered how to create a movie from time-lapse photographs, this is similar and takes the technique a couple of steps further.

Code

Full Code Gist Here

First, we need some modules.

OS and Shutil are for shell operations, because we need to call tools and create/delete folders.

import os
import shutil
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw

Next, we create the folder if it does not already exist, nuking the contents if it does.

We also create our image, loading in a background first.

if os.path.exists('frames'):
    shutil.rmtree('frames')
os.mkdir('frames')
img_background = Image.open('background.png')
img = Image.new("RGBA", img_background.size, (0, 0, 0, 255))

We need three colours, and a nice font.

x = 10
y = 10
silver = (100, 100, 100, 255)
purple = (100, 0, 200, 255)
white = (255, 255, 255, 255)
text = '''Boing!'''
font = ImageFont.truetype("/home/chrisg/Ubuntu-B.ttf", 75)
draw = ImageDraw.Draw(img)

Now we create the frames of animation, 24 frames for 1 second. All I am doing here is adding text to each frame in a different location, you can get wild in yours!

for N in range(0, 24):
    y += N
    img.paste(img_background, (0, 0))
    draw.text((x+4, y+4), text, purple, font=font)
    draw.text((x+2, y+2), text, silver, font=font)
    draw.text((x, y), text, white, font=font)
    img.save("./frames/{}.png".format(str(N).zfill(3)))

All that is left is to generate an AVI then convert to gif.

For higher quality we can come back and optimize the palette, but for simplicity this is sufficient for now!

os.system('ffmpeg -framerate 24 -i frames/%03d.png -c:v ffv1 -r 24 -y out.avi')
os.system('ffmpeg -y -i out.avi out.gif')
shutil.rmtree('frames')

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center