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