fix serious bug in import HTMLParser in Python > 3.4
[rainbowstream.git] / rainbowstream / c_image.py
... / ...
CommitLineData
1from PIL import Image
2from os.path import join, dirname, getmtime, exists, expanduser
3from .config import *
4
5import ctypes
6import sys
7import os
8
9
10def 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
23rgb2short = call_c()
24
25
26def 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
33def 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"""
62For direct using purpose
63"""
64if __name__ == '__main__':
65 image_to_display(sys.argv[1])