1 # -*- coding: utf-8 -*-
3 from os
.path
import join
, dirname
, getmtime
, exists
, expanduser
5 from .py3patch
import *
14 Call the C program for converting RGB to Ansi colors
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
)
23 return image_c
.rgb_to_ansi
28 def pixel_print(pixel
):
30 Print a pixel with given Ansi color
34 if c
['24BIT'] is True:
35 sys
.stdout
.write('\033[48;2;%d;%d;%dm \033[0m'
38 ansicolor
= rgb2short(r
, g
, b
)
39 sys
.stdout
.write('\033[48;5;%sm \033[0m' % (ansicolor
))
42 def block_print(higher
, lower
):
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.
47 r0
, g0
, b0
= lower
[:3]
48 r1
, g1
, b1
= higher
[:3]
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
))
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
))
59 def image_to_display(path
, start
=None, length
=None):
63 rows
, columns
= os
.popen('stty size', 'r').read().split()
65 start
= c
['IMAGE_SHIFT']
67 length
= int(columns
) - 2 * start
72 width
= min(w
, length
)
73 height
= int(float(h
) * (float(width
) / float(w
)))
75 if c
['IMAGE_RESIZE_TO_FIT'] is True:
76 # If it image won't fit in the terminal without scrolling shrink it
77 # Subtract 3 from rows so the tweet message fits in too.
78 h
= 2 * (int(rows
) - 3)
80 width
= int(float(width
) * (float(h
) / float(height
)))
82 if (height
<= 0) or (width
<= 0):
83 raise ValueError("image has negative dimensions")
85 i
= i
.resize((width
, height
), Image
.ANTIALIAS
)
86 height
= min(height
, c
['IMAGE_MAX_HEIGHT'])
88 for real_y
in xrange(height
// 2):
89 sys
.stdout
.write(' ' * start
)
90 for x
in xrange(width
):
92 p0
= i
.getpixel((x
, y
))
93 p1
= i
.getpixel((x
, y
+ 1))
95 sys
.stdout
.write('\n')
99 For direct using purpose
101 if __name__
== '__main__':
102 image_to_display(sys
.argv
[1])