Stawa
Stawa

Reputation: 325

PIL Python3 - How can I open a GIF file using Pillow?

In my current condition, I can open an Image normally using a really short code like this

from PIL import Image

x = Image.open("Example.png")
x.show()

But I tried to use GIF format instead of png, It shows the file but it didn't load the frame of the GIF. Is there any possible way to make load it?

In My Current Code

from PIL import Image

a = Image.open("x.gif").convert("RGBA") # IF I don't convert it to RGBA, It will give me an error.
a.show()

Upvotes: 1

Views: 10955

Answers (2)

Daraan
Daraan

Reputation: 3892

Another way to open gifs without visual-overhead of seek, tell and try is to use ImageSequence as a context manager:

from PIL import Image, ImageSequence

im = Image.open("x.gif")

for frame in ImageSequence.Iterator(im):
    ...

Upvotes: 0

Mark Setchell
Mark Setchell

Reputation: 207668

Refer to Reading Sequences in the documentation:

from PIL import Image

with Image.open("animation.gif") as im:
    im.seek(1)  # skip to the second frame

    try:
        while 1:
            im.seek(im.tell() + 1)
            # do something to im
    except EOFError:
        pass  # end of sequence

Upvotes: 2

Related Questions