Python, how i can get gif frames

Kula picture Kula · Sep 21, 2011 · Viewed 16.5k times · Source

I am looking some kind method to get gif frames number. I am looking on Google, StackOverflow and any other sites and I find only rubbish! Someone know how to do it? I need only simple number of gif frames.

Answer

Derek Springer picture Derek Springer · Sep 21, 2011

Which method are you using to load/manipulate the frame? Are you using PIL? If not, I suggest checking it out: Python Imaging Library and specifically the PIL gif page.

Now, assuming you are using PIL to read in the gif, it's a pretty simple matter to determine which frame you are looking at. seek will go to a specific frame and tell will return which frame you are looking at.

from PIL import Image
im = Image.open("animation.gif")

# To iterate through the entire gif
try:
    while 1:
        im.seek(im.tell()+1)
        # do something to im
except EOFError:
    pass # end of sequence

Otherwise, I believe you can only find the number of frames in the gif by seeking until an exception (EOFError) is raised.