Commit | Line | Data |
---|---|---|
0418d443 | 1 | from PIL import Image |
60431c3b | 2 | from functools import partial |
3 | from os.path import join, dirname, getmtime, exists, expanduser | |
816e305f | 4 | from .config import * |
60431c3b | 5 | |
991c30af O |
6 | import ctypes |
7 | import sys | |
8 | import os | |
9 | ||
60431c3b | 10 | |
11 | def call_c(): | |
12 | library = expanduser('~/.image.so') | |
13 | sauce = join(dirname(__file__), 'image.c') | |
14 | if not exists(library) or getmtime(sauce) > getmtime(library): | |
15 | build = "gcc -fPIC -shared -o %s %s" % (library, sauce) | |
16 | assert os.system(build + " >/dev/null 2>&1") == 0 | |
991c30af | 17 | image_c = ctypes.cdll.LoadLibrary(library) |
60431c3b | 18 | image_c.init() |
19 | return image_c.rgb_to_ansi | |
20 | ||
21 | rgb2short = call_c() | |
991c30af O |
22 | |
23 | ||
60431c3b | 24 | def pixel_print(ansicolor): |
25 | sys.stdout.write('\033[48;5;%sm \033[0m' % (ansicolor)) | |
991c30af O |
26 | |
27 | ||
60431c3b | 28 | def image_to_display(path): |
991c30af | 29 | i = Image.open(path) |
60431c3b | 30 | i = i.convert('RGBA') |
991c30af | 31 | w, h = i.size |
60431c3b | 32 | i.load() |
33 | rows, columns = os.popen('stty size', 'r').read().split() | |
816e305f | 34 | width = min(w, int(columns) - 2 * IMAGE_SHIFT) |
60431c3b | 35 | height = int(float(h) * (float(width) / float(w))) |
36 | height //= 2 | |
37 | i = i.resize((width, height), Image.BICUBIC) | |
816e305f | 38 | height = min(height, IMAGE_MAX_HEIGHT) |
60431c3b | 39 | |
40 | for y in xrange(height): | |
816e305f | 41 | print ' ' * IMAGE_SHIFT, |
60431c3b | 42 | for x in xrange(width): |
991c30af | 43 | p = i.getpixel((x, y)) |
60431c3b | 44 | r, g, b = p[:3] |
991c30af | 45 | pixel_print(rgb2short(r, g, b)) |
60431c3b | 46 | print '' |
47 | ||
48 | if __name__ == '__main__': | |
49 | image_to_display(sys.argv[1]) |