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(): | |
531f5682 O |
11 | """ |
12 | Call the C program for converting RGB to Ansi colors | |
13 | """ | |
60431c3b | 14 | library = expanduser('~/.image.so') |
15 | sauce = join(dirname(__file__), 'image.c') | |
16 | if not exists(library) or getmtime(sauce) > getmtime(library): | |
17 | build = "gcc -fPIC -shared -o %s %s" % (library, sauce) | |
18 | assert os.system(build + " >/dev/null 2>&1") == 0 | |
991c30af | 19 | image_c = ctypes.cdll.LoadLibrary(library) |
60431c3b | 20 | image_c.init() |
21 | return image_c.rgb_to_ansi | |
22 | ||
23 | rgb2short = call_c() | |
991c30af O |
24 | |
25 | ||
60431c3b | 26 | def pixel_print(ansicolor): |
531f5682 O |
27 | """ |
28 | Print a pixel with given Ansi color | |
29 | """ | |
60431c3b | 30 | sys.stdout.write('\033[48;5;%sm \033[0m' % (ansicolor)) |
991c30af O |
31 | |
32 | ||
422dd385 | 33 | def image_to_display(path, start=None, length=None): |
531f5682 O |
34 | """ |
35 | Display an image | |
36 | """ | |
4592d231 | 37 | rows, columns = os.popen('stty size', 'r').read().split() |
38 | if not start: | |
632c6fa5 | 39 | start = c['IMAGE_SHIFT'] |
4592d231 | 40 | if not length: |
41 | length = int(columns) - 2 * start | |
991c30af | 42 | i = Image.open(path) |
60431c3b | 43 | i = i.convert('RGBA') |
991c30af | 44 | w, h = i.size |
60431c3b | 45 | i.load() |
4592d231 | 46 | width = min(w, length) |
60431c3b | 47 | height = int(float(h) * (float(width) / float(w))) |
48 | height //= 2 | |
f5677fb1 | 49 | i = i.resize((width, height), Image.ANTIALIAS) |
632c6fa5 | 50 | height = min(height, c['IMAGE_MAX_HEIGHT']) |
60431c3b | 51 | |
77f1d210 | 52 | for y in range(height): |
c3bab4ef | 53 | sys.stdout.write(' ' * start) |
77f1d210 | 54 | for x in range(width): |
991c30af | 55 | p = i.getpixel((x, y)) |
60431c3b | 56 | r, g, b = p[:3] |
991c30af | 57 | pixel_print(rgb2short(r, g, b)) |
c3bab4ef | 58 | sys.stdout.write('\n') |
60431c3b | 59 | |
531f5682 O |
60 | |
61 | """ | |
62 | For direct using purpose | |
63 | """ | |
60431c3b | 64 | if __name__ == '__main__': |
65 | image_to_display(sys.argv[1]) |