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