Skip to content

Instantly share code, notes, and snippets.

@northernjamie
Last active November 6, 2022 12:05
Show Gist options
  • Save northernjamie/1545a9a0ef832bbcc05dee9c6c1a481a to your computer and use it in GitHub Desktop.
Save northernjamie/1545a9a0ef832bbcc05dee9c6c1a481a to your computer and use it in GitHub Desktop.
from PIL import Image
import glob
import time
# create an empty list called images
images = []
# get the current time to use in the filename
timestr = time.strftime("%Y%m%d-%H%M%S")
# get all the images in the 'images for gif' folder
for filename in sorted(glob.glob('outputs/images_for_gif/*.png')): # loop through all png files in the folder
im = Image.open(filename) # open the image
im_small = im.resize((1200, 1500), resample=0) # resize them to make them a bit smaller
images.append(im_small) # add the image to the list
# calculate the frame number of the last frame (ie the number of images)
last_frame = (len(images))
# create 10 extra copies of the last frame (to make the gif spend longer on the most recent data)
for x in range(0, 9):
im = images[last_frame-1]
images.append(im)
# save as a gif
images[0].save('outputs/weekly_utla_cases_' + timestr + '.gif',
save_all=True, append_images=images[1:], optimize=False, duration=500, loop=0)
@sgraaf
Copy link

sgraaf commented Sep 15, 2020

Hi Jamie! I just read your guide on making animated GIFs w/ Python. Though I am no export or authority on the matter, I noticed your code wasn't very "Pythonic"... I took a small stab at making it more so:

import time
from pathlib import Path

from PIL import Image

# create an empty list called images
images = []

# get the current time to use in the filename
timestr = time.strftime("%Y%m%d-%H%M%S")

# get all the images in the 'images for gif' folder
for filename in sorted(Path('outputs/images_for_gif').glob('*.png')): # loop through all png files in the folder
    im = Image.open(filename) # open the image
    im_small = im.resize((1200, 1500), resample=0) # resize them to make them a bit smaller
    images.append(im_small) # add the image to the list

# create 10 extra copies of the last frame (to make the gif spend longer on the most recent data)
last_im = images[-1]
for _ in range(10):
    images.append(last_im)

# or, alternatively, as a one-liner
# images += [last_im] * 10

# save as a gif   
images[0].save(
    f'outputs/weekly_utla_cases_{timestr}.gif',
    save_all=True,
    append_images=images[1:],
    optimize=False,
    duration=500,
    loop=0
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment