Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

怎样迭代 Pillow 的所有帧并保留处理结果?

查看完整题解

参考回答

直接回答

在 with Image.open(path) 内循环 ImageSequence.Iterator(im),访问每个帧。只做统计时可以直接读当前帧。要把若干帧留下来,立即 copy() 或 convert("RGBA")。

讲清原理

迭代器会移动同一个图像对象的帧位置。把循环变量直接加进列表,多个项可能指向同一对象。先复制才有各自独立的像素,时长也最好在对应帧上单独读取。

例子与易错点

例如把 GIF 拆成 PNG 时边迭代边保存可以限制内存。要重新合成为 GIF,则记录每帧时长,统一处理尺寸和输出模式。

from io import BytesIO

from PIL import Image, ImageSequence

frames = [Image.new("RGB", (8, 8), color) for color in ("red", "blue")]
buffer = BytesIO()
frames[0].save(buffer, format="GIF", save_all=True, append_images=frames[1:],
               duration=[100, 200], loop=0)
buffer.seek(0)
with Image.open(buffer) as im:
    copied = []
    durations = []
    for frame in ImageSequence.Iterator(im):
        durations.append(frame.info["duration"])
        copied.append(frame.convert("RGB"))
assert durations == [100, 200]
assert [f.getpixel((0, 0)) for f in copied] == [(255, 0, 0), (0, 0, 255)]
print(durations, "两帧像素已独立保留")

相关题:第 46 题、第 48 题、第 60 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。