mjk 134
mjk 134

Reputation: 33

How do I put a GIF ontop of a GIF in python

Im currently trying to put a gif ontop of a gif and then save it. I've tried this.

@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")

What this does is get an image from a url convert it into a gif format. Open a gif locally an trying to apply it to the converted gif.

Instead of what im expecting i get a weird non animated file.

image link> https://cdn.discordapp.com/attachments/738572311107469354/785428570205716491/iamge.gif

Please help. Using discord.py and Pillow.

Upvotes: 0

Views: 795

Answers (1)

furas
furas

Reputation: 142982

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 (wikipedia: Lenna)

enter image description here

salty.gif

enter image description here

image.gif

enter image description here

Upvotes: 2

Related Questions