修改GIF的所有帧-将其拆分成帧,处理每一帧,然后创建一个新的GIF。

5
我一直在尝试使用PIL/Pillow,但遇到了瓶颈。我一直在尝试将GIF拆分为帧,修改每个帧的颜色深度,然后再将这些帧合并成一个GIF。
下面是我的代码:
from PIL import Image

def gif_depth_change(pathToGIF, colourDepth):
    originalGIF = Image.open(pathToGIF)
    newGIF = originalGIF.convert("P", palette=Image.ADAPTIVE, colors=colourDepth)
    newGIF.show()
convert()方法在这里似乎不起作用,因为它只显示一个PNG图像,而没有给定作为参数的颜色深度。
我也尝试了这个:
def gif_depth_change(pathToGIF, colourDepth):
    originalGIF = Image.open(pathToGIF)
    newFrames = []
    for frame in range(0, originalGIF.n_frames):
        originalGIF.seek(frame)
        x = originalGIF.convert("P", palette=Image.ADAPTIVE, colors=colourDepth)
        newFrames.append(x)
    newFrames[0].save('changed-depth-gif.gif', format='GIF', append_images=newFrames[1:], save_all=True)

运行此代码时,它会将GIF文件保存下来,但不会对其进行任何修改(返回的是相同的GIF)。我还尝试在originalGIF.seek(frame)上使用convert(),但返回值为None


@user2864740 - 不好意思,我不确定为什么,但是我看到的所有教程都使用 frames[0],请参考链接链接 - rocketstar31
没错。这里是脑抽了。 - user2864740
1个回答

5

像这样:

from PIL import Image


def process_image(filename, color_depth):
    original = Image.open(filename)

    new = []
    for frame_num in range(original.n_frames):
        original.seek(frame_num)
        new_frame = Image.new('RGBA', original.size)
        new_frame.paste(original)
        new_frame = new_frame.convert(mode='P', palette=Image.ADAPTIVE, colors=color_depth)
        new.append(new_frame)

    new[0].save('new.gif', append_images=new[1:], save_all=True)


if __name__ == '__main__':
    process_image('test.gif', 4)

它循环遍历原始文件中的每一帧并创建副本,然后将其转换并添加到新帧列表中。然后将它们一起保存为单个gif文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接