➜ /tmp rmdir show_gif ➜ /tmp mkdir show_gif ➜ /tmp cd show_gif ➜ show_gif python3 -m venv ./venv ➜ show_gif . ./venv/bin/activate (venv) ➜ show_gif pip install Pillow Collecting Pillow Using cached Pillow-8.1.0-cp39-cp39-macosx_10_10_x86_64.whl (2.2 MB) Installing collected packages: Pillow Successfully installed Pillow-8.1.0 WARNING: You are using pip version 20.2.3; however, version 21.0.1 is available. You should consider upgrading via the '/private/tmp/show_gif/venv/bin/python3 -m pip install --upgrade pip' command.
接着便可以让它读入并解析一张GIF图片
1 2 3 4 5 6 7 8 9
import sys
from PIL import Image, ImageSequence
if __name__ == '__main__': path = sys.argv[1] im = Image.open(path) for frame in ImageSequence.Iterator(im): pass
然后将每一帧都转换为RGB模式再遍历其每一个像素
1 2 3 4 5 6 7 8 9 10 11 12 13
import sys
from PIL import Image, ImageSequence
if __name__ == '__main__': path = sys.argv[1] im = Image.open(path) for frame in ImageSequence.Iterator(im): rgb_frame = frame.convert('RGB') pixels = rgb_frame.load() for y inrange(0, rgb_frame.height): for x inrange(0, rgb_frame.width): pass
if __name__ == '__main__': path = sys.argv[1] im = Image.open(path) for frame in ImageSequence.Iterator(im): rgb_frame = frame.convert('RGB') pixels = rgb_frame.load() for y inrange(0, rgb_frame.height): for x inrange(0, rgb_frame.width): colors = pixels[x, y] print('\x1b[48;2;{};{};{}m \x1b[0m'.format(*colors), end='') print('')
在每次二重循环遍历了所有像素后,还必须清除输出的内容,并将光标重置到左上角才能再次打印,这可以用ASCII转义序列来实现。查阅VT100 User Guide可以知道,用ED命令可以擦除显示的字符,对应的转义序列为\x1b[2J;用CUP命令可以移动光标的位置到左上角,对应的转义序列为\x1b[0;0H。在每次开始打印一帧图像前输出这两个转义序列即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import sys
from PIL import Image, ImageSequence
if __name__ == '__main__': path = sys.argv[1] im = Image.open(path) for frame in ImageSequence.Iterator(im): rgb_frame = frame.convert('RGB') pixels = rgb_frame.load() print('\x1b[2J\x1b[0;0H', end='') for y inrange(0, rgb_frame.height): for x inrange(0, rgb_frame.width): colors = pixels[x, y] print('\x1b[48;2;{};{};{}m \x1b[0m'.format(*colors), end='') print('')
if __name__ == '__main__': path = sys.argv[1] im = Image.open(path) for frame in ImageSequence.Iterator(im): rgb_frame = frame.convert('RGB') pixels = rgb_frame.load() print('\x1b[2J\x1b[0;0H', end='') for y inrange(0, rgb_frame.height): last_colors = None line = '' for x inrange(0, rgb_frame.width): colors = pixels[x, y] if colors != last_colors: line += '\x1b[0m\x1b[48;2;{};{};{}m '.format(*colors) else: line += ' ' last_colors = colors print('{}\x1b[0m'.format(line)) time.sleep(rgb_frame.info['duration'] / 1000)