python - 使用 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>]
解决方案
正如其他人在评论中提到的那样,您发布的代码适用于最新的 Python + 枕头分布。您的枕头版本可能存在问题,此处提到了类似问题PIL.PngImagePlugin.PngImageFile images can't be save as GIFs in 7.1.1。
该问题的解决方案是
- 更新枕头
- .copy() 所有帧
- 使用 jpg 而不是 png。
推荐阅读
- ruby - Ruby ActiveRecord 获取到最后一个条目的范围?
- javascript - Jquery 步骤向导与 Image Uploader 冲突
- excel - 如何将 DataTable 导出到多个 Excel 文件?
- stata - 找到第二个最小值
- php - 使用 php 远程发布到 Wordpress 博客(最佳解决方案)
- sql - MsSQL 遍历结果以检查和获取更多数据
- ios - iOS - Swift 如何绘制带有双边框的 UIView,如故事板?
- php - addlashes 和 json_encode 不能一起工作
- postgresql - Postgresql:如何计算不同货币价格的AVE和SUM?
- javascript - 对嵌套数组进行排序