Png to animated Gif with Python

Png to Gif

We all like animated gif for different purposes, right? There are many softwares to do it maybe, but why not to try something made with python and some other free tools to help doing the job? It is quite easy, you can do it with a couple of lines of code. You gotta have the images, though. That is the hardest part. So, if you have them, it is quick, but if you don’t, you gotta make the images first and then convert them into an animated gif.

In the following chapter we will show how to convert some png images into gif, but in the latter chapter we will see an example of making the different png files with Python and the PIL module, instead of having to create them with some program, and it will be done in a couple of seconds.

The example will be limited to animation with text, but nothing can stop you from adding images to the png files.

Transform more existing pngs into an animated gif

This method uses just Python and PIL, the python imaging library, while the next one uses convert, another program, limiting Python to launch the command for that free program. If you choose to use just Python, the code is the following:

from PIL import Image
import glob

# Create the frames
frames = []
imgs = glob.glob("*.png")
for i in imgs:
    new_frame = Image.open(i)
    frames.append(new_frame)

# Save into a GIF file that loops forever
frames[0].save('png_to_gif.gif', format='GIF',
               append_images=frames[1:],
               save_all=True,
               duration=300, loop=0)

Whith the code above any png will be included in the animated gif with the duration set in the last lines of code.

Let’s make a practical example of usage of code to get animated gif from png image files

This is the example done in the video tutorial above.

Using the program convert to do the animated gif

In the following code you can create the gif using convert another free program. In this case Python is just launching commands to this program so that it does the convertion of the pngs into one animate gif, differentely from the code above where all work was done in Python using PIL, python imaging library.

# using convert through Python
import subprocess
import os

i = "*.png"
o = "output.gif"
subprocess.call("convert -delay 100 -loop 5 " + i + " " + o, shell=True)
os.system("start output.gif")

You will use convert to easily convert png to gif. You can change:

i = “*png” with any file type (jpg…)

-delay = 100 to modify the time between one frame and another

-loop 5 to tell how many times the image will be showed in sequence

and also the name of the output.gif file.

Png to Gif

Automate the creation of the single pngs needed for the animated gif

In the following code we create the images just with PIL, without having to save them, converting them into a gif in just one “passage”.

from PIL import Image, ImageDraw, ImageFont

fnt = ImageFont.truetype("arial", 36)
def create_image_with_text(wh, text):
    width, height = wh
    img = Image.new('RGB', (300, 200), "yellow")
    draw = ImageDraw.Draw(img)
    # draw.ellipse takes a 4-tuple (x0, y0, x1, y1) where (x0, y0) is the top-left bound of the box
    # and (x1, y1) is the lower-right bound of the box.
    draw.text((width, height), text, font = fnt, fill="black")
    return img
# Create the frames
frames = []
x, y = 0, 0
for i in range(100):
    new_frame = create_image_with_text((x-100,y), "HELLO")
    frames.append(new_frame)
    x += 4
    y += 1

# Save into a GIF file that loops forever
frames[0].save('moving_text.gif', format='GIF',
               append_images=frames[1:], save_all=True, duration=30, loop=0)

Moving balls: an example of gif generated by PIL

This example is taken from the page coming from this blog:

from PIL import Image, ImageDraw


def create_image_with_ball(width, height, ball_x, ball_y, ball_size):
    img = Image.new('RGB', (width, height), (255, 255, 255))
    draw = ImageDraw.Draw(img)
    # draw.ellipse takes a 4-tuple (x0, y0, x1, y1) where (x0, y0) is the top-left bound of the box
    # and (x1, y1) is the lower-right bound of the box.
    draw.ellipse((ball_x, ball_y, ball_x + ball_size, ball_y + ball_size), fill='red')
    return img
# Create the frames
frames = []
x, y = 0, 0
for i in range(10):
    new_frame = create_image_with_ball(400, 400, x, y, 40)
    frames.append(new_frame)
    x += 40
    y += 40

# Save into a GIF file that loops forever
frames[0].save('moving_ball.gif', format='GIF',
               append_images=frames[1:],
               save_all=True,
               duration=100, loop=0)

Moving text example

With some changes in the code you can make a text move on the screen (see the post about it and another one with cartoonish kind of animated banners).

More like this

If you want to see other examples about this type of ‘effect’ go to read this post about creating animated gifs with Python programming language I posted some days ago on this blog (25/07/2019).

Click here to go see some other examples about animated gif
Other examples of animated gifs

Even further

Lately I have added this post to create more engaging gif. Go check them clicking on the image below (taken from one of the output of the code present in the post itself):

animated gif from romeo and juliet test
Click on this banner to read the pythonprogramming.altervista.org post about animated gif (ps: this is not an ad banner it is just an example of animated gif made with Python and PIL)

I think I have just skratched the surface of this topic, so… to be continued?

Updated the 30th of July 2019 by Giovanni Python

Utilities

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.