如何用Linux显示动画gif?

use*_*974 8 python linux gif animated-gif python-imaging-library

我想在Linux中从python控制台打开一个GIF图像.通常在打开.png或时.jpg,我会做以下事情:

>>> from PIL import Image                                                                                
>>> img = Image.open('test.png')
>>> img.show()
Run Code Online (Sandbox Code Playgroud)

但如果我这样做:

>>> from PIL import Image                                                                                
>>> img = Image.open('animation.gif')
>>> img.show()
Run Code Online (Sandbox Code Playgroud)

Imagemagick将打开,但只显示gif的第一帧,而不是动画.

有没有办法在Linux中的查看器中显示GIF的动画?

unu*_*tbu 5

Image.show将映像转储到临时文件,然后尝试显示该文件.它打电话ImageShow.Viewer.show_image(见/usr/lib/python2.7/dist-packages/PIL/ImageShow.py):

class Viewer:
    def save_image(self, image):
        # save to temporary file, and return filename
        return image._dump(format=self.get_format(image))
    def show_image(self, image, **options):
        # display given image
        return self.show_file(self.save_image(image), **options)
    def show_file(self, file, **options):
        # display given file
        os.system(self.get_command(file, **options))
        return 1
Run Code Online (Sandbox Code Playgroud)

AFAIK,标准PIL 无法保存动画GIfs 1.

image._dump呼叫Viewer.save_image只保存第一帧.因此,无论后来调用哪个查看器,您只能看到静态图像.

如果你有Imagemagick的display程序,那么你也应该有它的animate程序.因此,如果您已经将GIF作为文件,那么您可以使用

animate /path/to/animated.gif
Run Code Online (Sandbox Code Playgroud)

要在Python中执行此操作,您可以使用子进程模块(而不是img.show):

import subprocess

proc = subprocess.Popen(['animate', '/path/to/animated.gif'])
proc.communicate()
Run Code Online (Sandbox Code Playgroud)

1 根据kostmo的说法,有一个用PIL保存动画GIFS的脚本.


要在不阻塞主进程的情况下显示动画,请使用单独的线程生成animate命令:

import subprocess
import threading

def worker():
    proc = subprocess.Popen(['animate', '/path/to/animated.gif'])
    proc.communicate()

t = threading.Thread(target = worker)
t.daemon = True
t.start()
# do other stuff in main process
t.join()
Run Code Online (Sandbox Code Playgroud)