GIFs have been around for a little over 20 years, and in that time, they’ve become the preferred format of communication for many. They can try to say more than words by not just depicting a quick action or response, but by also mimicking the tone and facial cues of the person or group trying to get their message across in an entertaining, informative way. This blog post is about how to programmatically generate video or animated GIF in Python. I’ll take you on an animated GIF-making journey. We’ll walk through the process of turning your video footage into a GIF, and then I’ll show you how to make an animated gif. Finally, I’ll run you through how to make a multi-frame image-based animated GIF from scratch using images or footage.

Topics covered in the blog post:

  1. Convert video to gif.
  2. How to create animated gifs.
  3. Create gifs using multiple images.
  4. Adding typewriter effect in a gif.

Prerequisites:

Python:

To create GIFs with Python you need to have python 3.5+ on your system, you can easily install Python in your system by going to https://www.python.org/downloads/, downloading and installing the software.

Imageio:

Imageio is a Python library for working with images. This software is designed to be easy to install and work across Windows, Mac, and Linux machines. It reads and writes animated images, volumetric data, and scientific formats. It’s open-source so it can be installed on any device with Python 3.5+. Also, the user interface provides several basic descriptive statistical measurements which allow you to choose the right kind of file format (jpeg, png, or BMP) based on the required image resolution and pixel density. To install imageio use the following command in your system

pip install imageio imageio-ffmpeg

Pil:

PIL stands for Python Imaging Library and it is a free and open-source collection of tools that are used to manipulate different types of images. This library is mainly designed to support, read and save(as well as import) SVG and rasters such as jpeg/BMP/png files at various resolutions. Some other image formats like tiff/xpm will be accessed via external libraries. PIL is available for Windows, Mac OS X, Linux, etc. To install PIL use the following command in your system

pip install pil

Note: Before installing the PIL library please check that your system does not have a pillow library because they cannot exist at the same time.

Step -1: Convert a video into a GIF

# import dependencies
import imageio
import os

# load the video file
clip = os.path.abspath('sample.mp4')

# create a function
def gifMkaker(inputPath, targetFormat):
    # giving a output path
    outputPath = os.path.splitext(inputPath)[0] + targetFormat

    print(f'converting {inputPath} \n to {outputPath}')

    reader = imageio.get_reader(inputPath)
    # define fps of the gif
    fps = reader.get_meta_data()['fps']

    writer = imageio.get_writer(outputPath, fps=fps)

    for frames in reader:
        writer.append_data(frames)
        print(f'Frame{frames}')
    print('done')
    writer.close()

gifMkaker(clip, '.gif')

Output

Step -2: Create an Animated GIF

For example, we are creating an animated gif that has an animated circle inside the square 

# import dependencies from PIL import Image, ImageDraw

images = []

width = 700
center = width // 2
color_1 = (255, 255, 255)
color_2 = (0, 0, 0)
max_radius = int(center * 1.5)
step = 8

for i in range(0, max_radius, step):
    im = Image.new('RGB', (width, width), color_1)
    draw = ImageDraw.Draw(im)
    draw.ellipse((center - i, center - i, center + i, center + i), fill=color_2)
    images.append(im)

for i in range(0, max_radius, step):
    im = Image.new('RGB', (width, width), color_2)
    draw = ImageDraw.Draw(im)
    draw.ellipse((center - i, center - i, center + i, center + i), fill=color_1)
    images.append(im)

images[0].save('animated.gif',
              save_all=True, format='GIF', append_images=images[1:], optimize=False, duration=40, loop=0)

Here’s the breakdown of the code above:

  1. Initialize an empty list in the image variable.
  2. Here we described the color width and radius of the gif.
  3. Creating a for loop for the gif so that it will run automatically.
  4. Save the frames using format=’GIF’ and append_images=frames[1:].
  5. Every frame will run for 40ms (duration=40).
  6. The GIF image will loop forever (loop=0).

Output

Step -3: Create a GIF using Images

To create an animated gif first let’s Get the images in .png format to stitch together and save them in a single folder and rename them with the ascending number.

For this tutorial, you can use PIL or convert, two programs that operate as Python add-ons that allow for image transformation features. You can also use just Python to perform these functions if you choose not to download any additional programs, 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 the png images 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)

Output

Step -4: Creating a GIF file with Text

Here we are creating a kind of animated gif file with text. It will show the text in typewrite effect.

Import dependencies

from PIL import Image, ImageDraw, ImageFont
from IPython.display import display, HTML
import os

Configure the look of the gif file

def create_image_with_text(size, text):
    img = Image.new('RGB', (600, 70), "black")
    draw = ImageDraw.Draw(img)
    draw.text((size[0], size[1]), text, font = fnt, fill="green")
    return img

Create the frames

frames = []

def roll(text):

    for i in range(len(text)+1):
        new_frame = create_image_with_text((0,0), text[:i])
        frames.append(new_frame)
 
fnt = ImageFont.truetype("arial", 36)

Add the text you want to display in the gif

TXT = """

Hello

How are you

My name is Neeraj

Welcome to geekyhuman

You can find a great tutorial on python

""".splitlines()

# text is a line of all text
[roll(text) for text in TXT]

Save it into a gif format that loops (loop=0) forever

frames[0].save('banner_a.gif', format='GIF',
              append_images=frames[1:], save_all=True, duration=60, loop=0)
os.startfile("banner_a.gif")

print('done')

Output

Final Words

We hope you enjoyed this tutorial on how to create GIFs with Python. Here we covered how to convert video to gif, how to create gifs using images, how to create animated gifs, and how to create a typewriter effect in a gif file. In other words, you can say that we learned how to programmatically generate video or animated GIF in Python With this knowledge, you can automate the creation of your animated GIFs for fun or for sharing with others. So what are you waiting for? Try it out today by copying and pasting the code into your Python interpreter!

Here are some useful tutorials that you can read: