Python, how i can get gif frames

2020-02-06 03:43发布

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

标签: python frame
2条回答
Evening l夕情丶
2楼-- · 2020-02-06 04:11

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.

查看更多
Rolldiameter
3楼-- · 2020-02-06 04:34

Just parse the file, gifs are pretty simple:

class GIFError(Exception): pass

def get_gif_num_frames(filename):
    frames = 0
    with open(filename, 'rb') as f:
        if f.read(6) not in ('GIF87a', 'GIF89a'):
            raise GIFError('not a valid GIF file')
        f.seek(4, 1)
        def skip_color_table(flags):
            if flags & 0x80: f.seek(3 << ((flags & 7) + 1), 1)
        flags = ord(f.read(1))
        f.seek(2, 1)
        skip_color_table(flags)
        while True:
            block = f.read(1)
            if block == ';': break
            if block == '!': f.seek(1, 1)
            elif block == ',':
                frames += 1
                f.seek(8, 1)
                skip_color_table(ord(f.read(1)))
                f.seek(1, 1)
            else: raise GIFError('unknown block type')
            while True:
                l = ord(f.read(1))
                if not l: break
                f.seek(l, 1)
    return frames
查看更多
登录 后发表回答