如何在Linux中显示动画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的动画呢?
2 个回答
3
在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动画。
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
据我所知,标准的 PIL 无法保存动画 GIF1。
在 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 根据 kostmo 的说法,有一个脚本可以用 PIL 保存动画 GIF。
为了在不阻塞主进程的情况下显示动画,可以使用一个单独的线程来启动 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()