首页 > 解决方案 > PIL Gif 生成未按预期工作

问题描述

我正在尝试做的事情:由于我对使用 PIL 库生成图像仍然很陌生,因此我决定尝试将图像放在 gif 之上。我可以使用的适当教程或参考资料并不多。

出了什么问题:通常不会生成 gif。这会给出IndexError: bytearray index out of range我不知道如何解决的错误。但是,有时会生成gif,但会出现一些错误。我在下面包含了其中一些 GIF。

Example1 这个不起作用

这个例子2不起作用

代码

@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:

咸味gif

标签: pythondiscord.pypython-imaging-library

解决方案


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

我不知道是否有办法使用 PIL 控制每一帧的调色板信息。

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

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


推荐阅读