Imagemagick & Pillow generate malformed GIF frames

前端 未结 3 1258
[愿得一人]
[愿得一人] 2021-01-23 01:16

I need to extract the middle frame of a gif animation.

Imagemagick:

convert C:\\temp\\orig.gif -coalesce C:\\temp\\frame.jpg

generates

3条回答
  •  太阳男子
    2021-01-23 01:23

    Ok, this script will find and save the middle frame of an animated GIF using Pillow.

    It will also display the duration of the GIF by counting the milliseconds of each frame.

    from PIL import Image
    
    def iter_frames(im):
        try:
            i = 0
            while 1:
                im.seek(i)
                frame = im.copy()
                if i == 0:
                    # Save pallete of the first frame
                    palette = frame.getpalette()
                else:
                    # Copy the pallete to the subsequent frames
                    frame.putpalette(palette)
                yield frame
                i += 1
        except EOFError:  # End of gif
            pass
    
    im = Image.open('animated.gif')
    middle_frame_pos = int(im.n_frames / 2)
    durations = []
    
    for i, frame in enumerate(iter_frames(im)):
        if i == middle_frame_pos:
            middle_frame = frame.copy()
    
        try:
            durations.append(frame.info['duration'])
        except KeyError:
            pass
    
    middle_frame.save('middle_frame.png', **frame.info)
    
    duration = float("{:.2f}".format(sum(durations)))
    print('Total duration: %d ms' % (duration))
    

    Helpful code:

    • Python: Converting GIF frames to PNG
    • https://github.com/alimony/gifduration

提交回复
热议问题