python - 如何用 Linux 显示动画 gif?

标签 python linux python-imaging-library gif animated-gif

我想在 Linux 中从 python 控制台打开 GIF 图像。通常在打开 .png.jpg 时,我会执行以下操作:

>>> from PIL import Image                                                                                
>>> img = Image.open('test.png')
>>> img.show()

但是如果我这样做:

>>> from PIL import Image                                                                                
>>> img = Image.open('animation.gif')
>>> img.show()

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

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

最佳答案

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

AFAIK,标准 PIL can not save animated GIfs 1

Viewer.save_image 中的 image._dump 调用仅保存第一帧。因此无论随后调用什么查看器,您都只能看到静态图像。

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

animate /path/to/animated.gif

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

import subprocess

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

1 According to 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()

关于python - 如何用 Linux 显示动画 gif?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9045802/

相关文章:

linux - 我可以在新磁盘上使用ubuntu lvm吗?

linux - 当 find 提供文件时如何在文件名中使用空格 cp 文件

python - 什么用户应该拥有我的 Python 脚本和应用程序目录?

Python 图像文本标签脚本

c++ - 如何直接从Google Map批量下载大量高分辨率卫星图片?

Python RegEx - Negative Lookahead 在 a 之后不起作用?量词

python - Python代码中的缩进问题

python - 我怎样才能确保我的测试触及代码库的每一行?

python - 测试图像中的像素

python - 如何在 Python Pillow 中设置字体的字距调整?