Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving an animated GIF in Pillow

Tags:

python

pillow

(Python 3.4, PIL 1.1.7, Pillow 2.5.1)

I expected this to copy the original GIF.

from PIL import Image
im = Image.open(filename)
im.save('temp.gif')

Instead, it saves the first frame as a still.

What am I doing wrong?

like image 994
leewz Avatar asked Jul 11 '14 01:07

leewz


People also ask

How do you save animated GIFs?

– Browse GIFs and find the GIF you like. – Click on the GIF to get its detailed page. – Then right-click on it and choose the “Save image as…” option. – Select a folder to save the GIF and rename the GIF file.

Does pillow support GIFs?

Pillow reads GIF87a and GIF89a versions of the GIF file format. The library writes files in GIF87a by default, unless GIF89a features are used or GIF89a is already in use. Files are written with LZW encoding.


2 Answers

Version that requires only pillow and works:

from PIL import Image

width = 300
height = 300
im1 = Image.new("RGBA", (width, height), (255, 0, 0))
im2 = Image.new("RGBA", (width, height), (255, 255, 0))
im3 = Image.new("RGBA", (width, height), (255, 255, 255))
im1.save("out.gif", save_all=True, append_images=[im2, im3], duration=100, loop=0)

using existing images:

from PIL import Image

im1 = Image.open('a.png')
im2 = Image.open('b.png')
im3 = Image.open('c.png')
im1.save("out.gif", save_all=True, append_images=[im2, im3], duration=100, loop=0)

And, as too low versions of pillow are silently failing here is as a bonus version with a library version check:

from packaging import version
from PIL import Image

im1 = Image.open('a.png')
im2 = Image.open('b.png')
im3 = Image.open('c.png')
if version.parse(Image.PILLOW_VERSION) < version.parse("3.4"):
    print("Pillow in version not supporting making animated gifs")
    print("you need to upgrade library version")
    print("see release notes in")
    print("https://pillow.readthedocs.io/en/latest/releasenotes/3.4.0.html#append-images-to-gif")
else:
    im1.save("out.gif", save_all=True, append_images=[
             im2, im3], duration=100, loop=0)
like image 61
reducing activity Avatar answered Sep 30 '22 21:09

reducing activity


One can see that the new version of gifmaker script simply uses save method with special kwargs for GIF.

As the documentation states (https://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html#saving-sequences):

When calling save(), if a multiframe image is used, by default only the first frame will be saved. To save all frames, the save_all parameter must be present and set to True.

If present, the loop parameter can be used to set the number of times the GIF should loop, and the duration parameter can set the number of milliseconds between each frame.

like image 40
mr. Y Avatar answered Sep 30 '22 19:09

mr. Y