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