doubled the resolution of images
[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 *
13e6b275 4from .py3patch import *
60431c3b 5
991c30af
O
6import ctypes
7import sys
8import os
9
60431c3b 10
11def call_c():
531f5682
O
12 """
13 Call the C program for converting RGB to Ansi colors
14 """
60431c3b 15 library = expanduser('~/.image.so')
16 sauce = join(dirname(__file__), 'image.c')
17 if not exists(library) or getmtime(sauce) > getmtime(library):
4a885ebf 18 build = "cc -fPIC -shared -o %s %s" % (library, sauce)
bb68c687 19 os.system(build + " >/dev/null 2>&1")
991c30af 20 image_c = ctypes.cdll.LoadLibrary(library)
60431c3b 21 image_c.init()
22 return image_c.rgb_to_ansi
23
24rgb2short = call_c()
991c30af
O
25
26
60431c3b 27def pixel_print(ansicolor):
531f5682
O
28 """
29 Print a pixel with given Ansi color
30 """
60431c3b 31 sys.stdout.write('\033[48;5;%sm \033[0m' % (ansicolor))
991c30af
O
32
33
a3cf675b
JH
34def block_print(lower, higher):
35 """
36 Print two pixels arranged above each other with Ansi color.
37 Abuses Unicode to print two pixels in the space of one terminal block.
38 """
39 sys.stdout.write('\033[38;5;%sm\033[48;5;%smâ–„\033[0m' % (higher, lower))
40
41
422dd385 42def image_to_display(path, start=None, length=None):
531f5682
O
43 """
44 Display an image
45 """
4592d231 46 rows, columns = os.popen('stty size', 'r').read().split()
47 if not start:
632c6fa5 48 start = c['IMAGE_SHIFT']
4592d231 49 if not length:
50 length = int(columns) - 2 * start
991c30af 51 i = Image.open(path)
60431c3b 52 i = i.convert('RGBA')
991c30af 53 w, h = i.size
60431c3b 54 i.load()
4592d231 55 width = min(w, length)
60431c3b 56 height = int(float(h) * (float(width) / float(w)))
57 height //= 2
f5677fb1 58 i = i.resize((width, height), Image.ANTIALIAS)
632c6fa5 59 height = min(height, c['IMAGE_MAX_HEIGHT'])
60431c3b 60
a3cf675b 61 for real_y in xrange(height // 2):
c3bab4ef 62 sys.stdout.write(' ' * start)
13e6b275 63 for x in xrange(width):
a3cf675b
JH
64 y = real_y * 2
65 p0 = i.getpixel((x, y))
66 p1 = i.getpixel((x, y+1))
67 r0, g0, b0 = p0[:3]
68 r1, g1, b1 = p1[:3]
69 block_print(rgb2short(r0, g0, b0), rgb2short(r1, g1, b1))
c3bab4ef 70 sys.stdout.write('\n')
60431c3b 71
531f5682
O
72
73"""
74For direct using purpose
75"""
60431c3b 76if __name__ == '__main__':
77 image_to_display(sys.argv[1])