简体   繁体   English

使用 PIL/Pillow 制作 GIF

[英]Making a GIF using PIL/Pillow

I am trying to use PIL/Pillow to covert a number of .png files into a gif.我正在尝试使用 PIL/Pillow 将许多 .png 文件转换为 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我试过按顺序重命名文件(1.png、2.png、3.png 等),但这没有用

Any Ideas?有任何想法吗?

If you renamed your files starting with numbers, you could try to sort the imgs list.如果您重命名以数字开头的文件,则可以尝试对imgs列表进行排序。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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