add support for python 3
[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 *
60431c3b 4
991c30af
O
5import ctypes
6import sys
7import os
8
60431c3b 9
10def 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
20rgb2short = call_c()
991c30af
O
21
22
60431c3b 23def pixel_print(ansicolor):
24 sys.stdout.write('\033[48;5;%sm \033[0m' % (ansicolor))
991c30af
O
25
26
4592d231 27def image_to_display(path,start=None,length=None):
28 rows, columns = os.popen('stty size', 'r').read().split()
29 if not start:
632c6fa5 30 start = c['IMAGE_SHIFT']
4592d231 31 if not length:
32 length = int(columns) - 2 * start
991c30af 33 i = Image.open(path)
60431c3b 34 i = i.convert('RGBA')
991c30af 35 w, h = i.size
60431c3b 36 i.load()
4592d231 37 width = min(w, length)
60431c3b 38 height = int(float(h) * (float(width) / float(w)))
39 height //= 2
f5677fb1 40 i = i.resize((width, height), Image.ANTIALIAS)
632c6fa5 41 height = min(height, c['IMAGE_MAX_HEIGHT'])
60431c3b 42
43 for y in xrange(height):
c3bab4ef 44 sys.stdout.write(' ' * start)
60431c3b 45 for x in xrange(width):
991c30af 46 p = i.getpixel((x, y))
60431c3b 47 r, g, b = p[:3]
991c30af 48 pixel_print(rgb2short(r, g, b))
c3bab4ef 49 sys.stdout.write('\n')
60431c3b 50
51if __name__ == '__main__':
52 image_to_display(sys.argv[1])