python - 通过 PIL 将图像转换为动画 webp 文件时出错

标签 python python-imaging-library webp

我尝试过的两种方式:

  1. 将 PIL.Images 列表保存为 webp 文件:
from PIL import Image
import os
frames = []
fdir = "./frames"
for f in sorted(os.listdir(fdir)):
    f = os.path.join(fdir, f)
    frames.append(Image.open(f)) 
frames = frames[:100]
frames[0].save("./test.webp", "webp", save_all=True, append_images=frames[1:])

我得到了错误:

Traceback (most recent call last):
  File "/Users/feiyangsuo/anaconda3/envs/video/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3441, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-11-e3361ee93efc>", line 1, in <module>
    frames[0].save("./test.webp", "webp", save_all=True, append_images=frames[1:])
  File "/Users/feiyangsuo/anaconda3/envs/video/lib/python3.8/site-packages/PIL/Image.py", line 2172, in save
    save_handler(self, fp, filename)
  File "/Users/feiyangsuo/anaconda3/envs/video/lib/python3.8/site-packages/PIL/WebPImagePlugin.py", line 292, in _save_all
    timestamp += duration
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
  1. 将 gif 文件保存到 webp:
frames[0].save("./test.gif", "gif", save_all=True, append_images=frames[1:])  # this works fine
jb = Image.open("./test.gif")
jb.save("./test.webp", "webp", save_all=True)

我得到了和上面一样的错误。

我正在使用 PIL 8.2.0。该错误似乎来自 PIL 的基本实现,所以我不知道如何修改我的代码。

最佳答案

通过将 duration 参数添加到 save 函数来解决此问题。

例如

jb = Image.open("./test.gif")
jb.save("./test.webp", "webp", save_all=True, duration=10)

对于.gif,此参数可能为默认值,因此无需手动设置。

关于python - 通过 PIL 将图像转换为动画 webp 文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68250397/

相关文章:

python - 如何修复 "AttributeError: ' JpegImageFile' 对象没有属性 'read' ?

django - 如何解决 OSError : decoder jpeg not available on centos 7

python - 如何将8bit(0-255)数据表保存为图像文件,然后从图像中检索数据?

Android 将 gif 转换为动画 webp

python - 一行输出字典

python - 如果列存在于 df 中,如何根据条件删除 Pandas 中的列数据框 (df)?

python - PIL Image Convert from RGB to YCbCr Results in 4 Channels 而不是 3 并且表现得像 RGB

delphi - 如何在 TImage 或 TBitmap 中显示 WebP 图像?

python - 我如何在预测阶段获得所有输出 keras 层(特征图)?

python - 类型错误 : 'list' object is not callable while trying to access a list