首页 > 解决方案 > 使用 PIL 从许多 png 文件中生成 gif

问题描述

我正在尝试使用此解决方案将许多 png 图像组合成一个 gif 文件,但它只在 gif 中保存一个 png。我究竟做错了什么?我的 MWE 是

from PIL import Image, ImageDraw
import matplotlib.pyplot as plt
import numpy as np
import glob

thist = 4 # total time
tstep = 0 # time step

while thist>=tstep:

    x = np.linspace(0,2,100)
    y = np.sin(x*(thist-tstep)) # complicated calculation

    fig = plt.figure(figsize=(10,6))
    ax = plt.subplot(111)

    plt.plot(x,y)
    plt.savefig('mytest'+str(tstep)+'.png')

    tstep += 1

fp_in = "mytest*.png"
fp_out = "myimage.gif"

# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img, *imgs = [Image.open(f) for f in sorted(glob.glob(fp_in))]
img.save(fp=fp_out, format='GIF', append_images=imgs,
         save_all=True, duration=200, loop=0)

此外,

>> print(glob.glob(fp_in))

['mytest0.png', 'mytest1.png', 'mytest2.png', 'mytest3.png', 'mytest4.png']

>> print(imgs)

[<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=1000x600 at 0x7F8FCEB33240>, <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=1000x600 at 0x7F8FCEB33400>, <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=1000x600 at 0x7F8FCEB33470>, <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=1000x600 at 0x7F8FCEBACB38>]

标签: pythonmatplotlibanimationpython-imaging-library

解决方案


正如其他人在评论中提到的那样,您发布的代码适用于最新的 Python + 枕头分布。您的枕头版本可能存在问题,此处提到了类似问题PIL.PngImagePlugin.PngImageFile images can't be save as GIFs in 7.1.1

该问题的解决方案是

  1. 更新枕头
  2. .copy() 所有帧
  3. 使用 jpg 而不是 png。

推荐阅读