| 1 | from PIL import Image |
| 2 | from os.path import join, dirname, getmtime, exists, expanduser |
| 3 | from .config import * |
| 4 | |
| 5 | import ctypes |
| 6 | import sys |
| 7 | import os |
| 8 | |
| 9 | |
| 10 | def call_c(): |
| 11 | """ |
| 12 | Call the C program for converting RGB to Ansi colors |
| 13 | """ |
| 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 |
| 19 | image_c = ctypes.cdll.LoadLibrary(library) |
| 20 | image_c.init() |
| 21 | return image_c.rgb_to_ansi |
| 22 | |
| 23 | rgb2short = call_c() |
| 24 | |
| 25 | |
| 26 | def pixel_print(ansicolor): |
| 27 | """ |
| 28 | Print a pixel with given Ansi color |
| 29 | """ |
| 30 | sys.stdout.write('\033[48;5;%sm \033[0m' % (ansicolor)) |
| 31 | |
| 32 | |
| 33 | def image_to_display(path, start=None, length=None): |
| 34 | """ |
| 35 | Display an image |
| 36 | """ |
| 37 | rows, columns = os.popen('stty size', 'r').read().split() |
| 38 | if not start: |
| 39 | start = c['IMAGE_SHIFT'] |
| 40 | if not length: |
| 41 | length = int(columns) - 2 * start |
| 42 | i = Image.open(path) |
| 43 | i = i.convert('RGBA') |
| 44 | w, h = i.size |
| 45 | i.load() |
| 46 | width = min(w, length) |
| 47 | height = int(float(h) * (float(width) / float(w))) |
| 48 | height //= 2 |
| 49 | i = i.resize((width, height), Image.ANTIALIAS) |
| 50 | height = min(height, c['IMAGE_MAX_HEIGHT']) |
| 51 | |
| 52 | for y in range(height): |
| 53 | sys.stdout.write(' ' * start) |
| 54 | for x in range(width): |
| 55 | p = i.getpixel((x, y)) |
| 56 | r, g, b = p[:3] |
| 57 | pixel_print(rgb2short(r, g, b)) |
| 58 | sys.stdout.write('\n') |
| 59 | |
| 60 | |
| 61 | """ |
| 62 | For direct using purpose |
| 63 | """ |
| 64 | if __name__ == '__main__': |
| 65 | image_to_display(sys.argv[1]) |