简体   繁体   中英

Making a GIF using PIL/Pillow

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM