PIL Gif 生成未按预期工作

PIL Gif generation not working as expected

我想做什么:由于我对使用 PIL 库生成图像还很陌生,所以我决定尝试将图像放在 gif 文件之上。我可以使用的适当教程或参考资料不多。

出了什么问题:gif 通常不会生成。这将给出错误 IndexError: bytearray index out of range,我不确定如何修复。但是有时候gif生成了,但是会出现一些错误。我在下面包含了其中一些 gif。

代码:

@client.command()
async def salt(ctx, user:discord.Member=None):
    if user == None:
        user = ctx.author

    animated_gif = Image.open("salty.gif")
    response = requests.get(user.avatar_url)
    background = Image.open(BytesIO(response.content))
    
    all_frames = []
#    background = background.resize((500, 500))

    for gif_frame in ImageSequence.Iterator(animated_gif):

        # duplicate background image
        new_frame = background.copy()  

        # need to convert from `P` to `RGBA` to use it in `paste()` as mask for transparency
        gif_frame = gif_frame.convert('RGBA')  

        # paste on background using mask to get transparency 
        new_frame.paste(gif_frame, mask=gif_frame) 

        all_frames.append(new_frame)
        
    # save all frames as animated gif
    all_frames[0].save("image.gif", save_all=True, append_images=all_frames[1:], duration=50, loop=0)

这是我正在使用的 gif:

不幸的是,PIL 中的动画 GIF 支持是错误的,并且很难使用。您显示的图像受到与背景图层共享调色板信息的图层的影响,因此它们的某些颜色失真。

不知道有没有办法用PIL来控制每一帧的调色板信息。

如果您想使用 Python 以编程方式生成 GIF,我现在建议您使用 GIMP 图像编辑器 - 在那里您可以构建图像,可以使用该程序以交互方式或以编程方式,使用 Python 控制台,然后调用“另存为 gif”功能 (pdb.file_gif_save2)。

(我将查看 PIL 的确切功能,并检查我是否可以扩展关于正确处理透明度的答案 - 否则,GIMP 是可行的方法)