【问题标题】:Making a GIF using PIL/Pillow使用 PIL/Pillow 制作 GIF
【发布时间】:2020-03-06 18:52:13
【问题描述】:

我正在尝试使用 PIL/Pillow 将多个 .png 文件转换为 gif。以下脚本正在运行,但正在以随机顺序添加帧。

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)

我尝试按顺序重命名文件(1.png、2.png、3.png 等),但这没有奏效

有什么想法吗?

【问题讨论】:

  • 检查this question,我觉得很有用。
  • glob.glob() 返回的名称顺序实际上是随机的,因此您需要某种方式对它们进行排序。您可以通过重命名它们以便按照您想要的顺序排序,然后您可以使用for i in sorted(imgs):

标签: python python-imaging-library


【解决方案1】:

如果您重命名了以数字开头的文件,您可以尝试对imgs 列表进行排序。不过,您可能需要使用自然顺序,具体取决于您命名文件的方式。

基于此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)

在你的代码中:

# Create frames
frames = []
imgs = glob.glob("*.png")
imgs = natural_sort(imgs)
for i in imgs:
    new_frame = Image.open(i)
    frames.append(new_frame)

【讨论】: