a1395f3acfe53fd81b0561e9a4c5ad833c631fbc
[rainbowstream.git] / rainbowstream / c_image.py
1 from PIL import Image
2 from os.path import join, dirname, getmtime, exists, expanduser
3 from .config import *
4 from .py3patch import *
5
6 import ctypes
7 import sys
8 import os
9
10
11 def call_c():
12 """
13 Call the C program for converting RGB to Ansi colors
14 """
15 library = expanduser('~/.image.so')
16 sauce = join(dirname(__file__), 'image.c')
17 if not exists(library) or getmtime(sauce) > getmtime(library):
18 build = "cc -fPIC -shared -o %s %s" % (library, sauce)
19 os.system(build + " >/dev/null 2>&1")
20 image_c = ctypes.cdll.LoadLibrary(library)
21 image_c.init()
22 return image_c.rgb_to_ansi
23
24 rgb2short = call_c()
25
26
27 def pixel_print(pixel):
28 """
29 Print a pixel with given Ansi color
30 """
31 r, g, b = pixel[:3]
32 ansicolor = rgb2short(r, g, b)
33 sys.stdout.write('\033[48;5;%sm \033[0m' % (ansicolor))
34
35
36 def block_print(higher, lower):
37 """
38 Print two pixels arranged above each other with Ansi color.
39 Abuses Unicode to print two pixels in the space of one terminal block.
40 """
41 r0, g0, b0 = lower[:3]
42 r1, g1, b1 = higher[:3]
43
44 if c['24BIT'] is True:
45 sys.stdout.write('\033[38;2;%d;%d;%dm\033[48;2;%d;%d;%dm▄\033[0m'
46 % (r1, g1, b1, r0, g0, b0))
47 else:
48 i0 = rgb2short(r0, g0, b0)
49 i1 = rgb2short(r1, g1, b1)
50 sys.stdout.write('\033[38;5;%sm\033[48;5;%sm▄\033[0m' % (i1, i0))
51
52
53 def image_to_display(path, start=None, length=None):
54 """
55 Display an image
56 """
57 rows, columns = os.popen('stty size', 'r').read().split()
58 if not start:
59 start = c['IMAGE_SHIFT']
60 if not length:
61 length = int(columns) - 2 * start
62 i = Image.open(path)
63 i = i.convert('RGBA')
64 w, h = i.size
65 i.load()
66 width = min(w, length)
67 height = int(float(h) * (float(width) / float(w)))
68 if c['HIGHER_RESOLUTION'] is False:
69 height //= 2
70 i = i.resize((width, height), Image.ANTIALIAS)
71 height = min(height, c['IMAGE_MAX_HEIGHT'])
72
73 if c['HIGHER_RESOLUTION'] is True:
74 for real_y in xrange(height // 2):
75 sys.stdout.write(' ' * start)
76 for x in xrange(width):
77 y = real_y * 2
78 p0 = i.getpixel((x, y))
79 p1 = i.getpixel((x, y+1))
80 block_print(p1, p0)
81 sys.stdout.write('\n')
82 else:
83 for y in xrange(height):
84 sys.stdout.write(' ' * start)
85 for x in xrange(width):
86 p = i.getpixel((x, y))
87 pixel_print(p)
88 sys.stdout.write('\n')
89
90
91 """
92 For direct using purpose
93 """
94 if __name__ == '__main__':
95 image_to_display(sys.argv[1])