How to Create Animated Gifs with Python

in #python7 years ago (edited)

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')

Sort:  

Awesome.
I've created animated gifs from the command line a few times. It might be a pain in the ass, but there's a lot that you can do surprisingly easily if you take the time to look up how. I've never really done it with python though. Always thought about creating a tool to help me make gifs, but never got around to it.

Perhaps I should mess around with doing some stuff and create a little library of useful bits of code for making little fun gifs. :)

Share when you do :D

Thanks for Lesson! I would Surely Try to Make it with python and share it with you 😊

I am still learning it. I am practicing it but never posted. It is very hard. I have to familiarize & understand the commands. Thanks for the post another info.