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