1

I am trying to use PIL/Pillow to covert a number of .png files into a gif. The following script is working but is adding the frames in random order.

from PIL import Image
import glob

# Create 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('globe.gif', format='GIF', 
               append_images=frames[0:], save_all=True, duration=1000, 
               loop=0, optimize=False, transparency=0)

I've tried renaming the files in order (1.png, 2.png, 3.png etc) but this hasn't worked

Any Ideas?

martineau
  • 119,623
  • 25
  • 170
  • 301
jhowell96
  • 11
  • 3
  • check [this question](https://stackoverflow.com/questions/753190/programmatically-generate-video-or-animated-gif-in-python), I think it can be usefull. – Majid A Mar 06 '20 at 10:53
  • The order of the names `glob.glob()` returns is effectively random, so you will need some way of ordering them. You can do this by renaming them so that they sort in the order you want, then you can use `for i in sorted(imgs):`. – martineau Mar 06 '20 at 11:22

1 Answers1

0

If you renamed your files starting with numbers, you could try to sort the imgs list. You might need to use a natural order though, depending on how you named your files.

Based on this answer :

import re

def natural_sort(l): 
    convert = lambda text: int(text) if text.isdigit() else text.lower() 
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 
    return sorted(l, key = alphanum_key)

And in your code :

# Create frames
frames = []
imgs = glob.glob("*.png")
imgs = natural_sort(imgs)
for i in imgs:
    new_frame = Image.open(i)
    frames.append(new_frame)
Lescurel
  • 10,749
  • 16
  • 39