修改 GIF 中的所有帧 - 拆分为帧、处理每个帧并创建新的 GIF

roc*_*r31 5 python gif python-imaging-library

我一直在尝试 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()
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

运行时,此代码会保存一个 GIF,但不会以任何方式修改它(它给了我相同的 GIF)。我也尝试使用convert()onoriginalGIF.seek(frame)但返回了None

T.W*_*.W. 6

像这样:

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)
Run Code Online (Sandbox Code Playgroud)

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