7

Basically I am using following piece of code to make gif out of images, my images are png with transparent background but the gif is with black background. I dont know how to make the gif with transparent background.

#gif writer
with io.get_writer('my.gif', mode='I', duration=0.1) as writer:
    for filename in file_names:
        image = io.imread(filename)
        writer.append_data(image)
#writer.close()

where filenames is an array with all the names of file to be used.

jkhadka
  • 2,443
  • 8
  • 34
  • 56

1 Answers1

13

try PIL

from PIL import Image

def gen_frame(path):
    im = Image.open(path)
    alpha = im.getchannel('A')

    # Convert the image into P mode but only use 255 colors in the palette out of 256
    im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)

    # Set all pixel values below 128 to 255 , and the rest to 0
    mask = Image.eval(alpha, lambda a: 255 if a <=128 else 0)

    # Paste the color of index 255 and use alpha as a mask
    im.paste(255, mask)

    # The transparency index is 255
    im.info['transparency'] = 255

    return im


im1 = gen_frame('frame1.png')
im2 = gen_frame('frame2.png')        
im1.save('GIF.gif', save_all=True, append_images=[im2], loop=5, duration=200)
FelixHo
  • 1,254
  • 14
  • 26
  • Thanks this works great. I need to change a bit, as some of my figure is also removed with the above pixel reset. But it works ! :) – jkhadka Jul 20 '18 at 11:02
  • 1
    `disposal` is missing from the `save` function, refer to [this](https://stackoverflow.com/questions/55313887/pil-is-showing-all-the-previous-frames-in-the-gif). Missing `disposal` will cause transparent frames to stack over previous ones. – Neil Z. Shao Apr 19 '19 at 12:48
  • This is terribly convoluted, is there really no better way!? – xjcl Jan 14 '20 at 06:14
  • 1
    I tested this solution and it didn't work for some gifs. The issue was, that PIL tries to optimize the pallet again during the save process, which can change the transparency index. To avoid this, you need to pass `optimize=False` to the save function. – arthaigo May 30 '20 at 13:52