【问题标题】:How to display an animated gif with Linux?如何使用 Linux 显示动画 gif?
【发布时间】:2017-11-30 10:26:46
【问题描述】:

我想从 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 的动画?

【问题讨论】:

  • 你的操作系统是什么? img.show() 在 Win32 和 Mac 上将临时图像转换为 BMP 格式。

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


【解决方案1】:

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 GIfs1

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()

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

【讨论】:

  • 好的。谢谢。无论如何,我注意到在您关闭 ImageMagick 窗口之前,python 脚本不会继续......有没有办法解决这个问题?
【解决方案2】:

linux打开一个gif

我用 Fedora 17 做到了这一点:

el@defiant ~ $ sudo yum install gifview
---> Package gifview.x86_64 0:1.67-1.fc17 will be installed

curl http://i.imgur.com/4rBHtSm.gif > mycat.gif

gifview mycat.gif

会出现一个窗口,您可以逐步浏览 gif 的帧。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-25
    • 2010-09-22
    • 1970-01-01
    • 2019-01-04
    • 2016-08-23
    • 2012-09-15
    相关资源
    最近更新 更多