首页 > 解决方案 > 如何在python中将GIF放在GIF之上

问题描述

我目前正在尝试将 gif 放在 gif 之上,然后保存它。我试过这个。

@client.command()
async def salt(ctx, member: discord.Member):
    response = requests.get(member.avatar_url)
    img = Image.open(BytesIO(response.content))
    
    framess = []
    framess.append(img)
    
    framess[0].save('png_to_gif.gif', format='GIF',
                append_images=framess[1:],
                save_all=True,
                duration=100, loop=0)
    
    new_Igf = Image.open('png_to_gif.gif')

    animated_gif = Image.open("salty.gif")
    frames = []
    for frame in ImageSequence.Iterator(new_Igf):
        frame = frame.copy()
        frame.paste(animated_gif)
        frames.append(frame)
        frames[0].save("iamge.gif")

这样做是从 url 获取图像并将其转换为 gif 格式。在本地打开一个 gif 并尝试将其应用于转换后的 gif。

而不是我所期望的,我得到一个奇怪的非动画文件。

图片链接> https://cdn.discordapp.com/attachments/738572311107469354/785428570205716491/iamge.gif

请帮忙。使用 discord.py 和 Pillow。

标签: pythonpython-imaging-librarydiscord.py

解决方案


from PIL import Image, ImageSequence

# load image    
background   = Image.open('lenna.png')#.convert('RGBA')
animated_gif = Image.open("salty.gif")

all_frames = []

for gif_frame in ImageSequence.Iterator(animated_gif):

    # duplicate background image because we will change it
    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)

lenna.png(维基百科:Lenna

在此处输入图像描述

咸的.gif

在此处输入图像描述

图片.gif

在此处输入图像描述


推荐阅读