使用 PIL 从许多 png 文件生成 gif
Using PIL to generate gif from many png files
我正在尝试使用此 solution 将许多 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>]
正如其他人在评论中提到的,您发布的代码适用于最新的 Python + pillow 发行版。您的枕头版本可能存在问题,此处提到了类似问题 PIL.PngImagePlugin.PngImageFile images can't be saved as GIFs in 7.1.1。
该问题的解决方案是
- 更新枕头
- .copy() 所有帧
- 使用 jpg 而不是 png。
我正在尝试使用此 solution 将许多 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>]
正如其他人在评论中提到的,您发布的代码适用于最新的 Python + pillow 发行版。您的枕头版本可能存在问题,此处提到了类似问题 PIL.PngImagePlugin.PngImageFile images can't be saved as GIFs in 7.1.1。
该问题的解决方案是
- 更新枕头
- .copy() 所有帧
- 使用 jpg 而不是 png。