Search code examples
pythonpython-3.xpython-imaging-librarygifanimated-gif

Transparency problem during making GIF from PNG on Pillow


I use Pillow to make a GIF. My output looks like that, previous images are binding because of transparency.

Output GIF

My code is:

import shutil
from PIL import Image
from .helpers import *


def animate(anifile=None, width=None, height=None, loop=None, bonds_param=None):
    if width is None:
        width = 1920
    if height is None:
        height = 1080
    if loop is None:
        loop = 0
    if bonds_param is None:
        bonds_param = 1.3
    fname = anifile.split(".")[0]
    frames = []
    imgfiles = write_pngs(write_xyzs(split_ani(anifile)), width, height, bonds_param)
    for imgfile in imgfiles:
        new_frame = Image.open(imgfile)
        frames.append(new_frame)
    frames[0].save(f'{fname}.gif', format='GIF',
                   append_images=frames[1:],
                   save_all=True,
                   duration=300, loop=loop)
    shutil.rmtree("ANIAnimator_temp")

How to prevent this binding? What is the correct code?


Solution

  • I made it with the setting disposal=2.

    import shutil
    from PIL import Image
    from .helpers import *
    
    
    def animate(anifile=None, width=None, height=None, loop=None, bonds_param=None):
        if width is None:
            width = 1920
        if height is None:
            height = 1080
        if loop is None:
            loop = 0
        if bonds_param is None:
            bonds_param = 1.3
        fname = anifile.split(".")[0]
        frames = []
        imgfiles = write_pngs(write_xyzs(split_ani(anifile)), width, height, bonds_param)
        print()
        for i, imgfile in enumerate(imgfiles):
            print(f"Creating GIF ({i + 1}/{len(imgfiles)})", end="\r")
            new_frame = Image.open(imgfile)
            frames.append(new_frame)
        frames[0].save(f"{fname}.gif", format="GIF",
                       append_images=frames[1:],
                       save_all=True,
                       duration=300,
                       loop=loop,
                       disposal=2)
        print(f"\n{fname}.gif is created")
        print(f"Deleting directory ANIAnimator_temp")
        shutil.rmtree("ANIAnimator_temp")
        print(f"Directory ANIAnimator_temp is deleted")
    

    The output image