2 from functools
import partial
4 from .py3patch
import *
10 This file is borrowed from following gist:
11 https://gist.github.com/MicahElliott/719710
12 It's too slow in compare with C program.
15 CLUT
= [ # color look-up table
18 # Primary 3-bit (8 colors). Unique representation!
28 # Equivalent "bright" versions of original 8 colors.
288 short2rgb_dict
= dict(CLUT
)
290 for k
, v
in short2rgb_dict
.items():
291 rgb2short_dict
[v
] = k
292 return rgb2short_dict
, short2rgb_dict
294 RGB2SHORT_DICT
, SHORT2RGB_DICT
= _create_dicts()
297 def short2rgb(short
):
301 return SHORT2RGB_DICT
[short
]
304 def pixel_print(ansicolor
):
306 Print a pixel with given Ansi color
308 sys
.stdout
.write('\033[48;5;%sm \033[0m' % (ansicolor
))
311 def hex_to_rgb(value
):
315 value
= value
.lstrip('#')
317 return tuple(int(value
[i
:i
+ lv
/ 3], 16) for i
in xrange(0, lv
, lv
/ 3))
324 return '%02x%02x%02x' % rgb
327 def rgb2short(r
, g
, b
):
331 dist
= lambda s
, d
: (s
[0] - d
[0]) ** 2 + \
332 (s
[1] - d
[1]) ** 2 + (s
[2] - d
[2]) ** 2
333 ary
= [hex_to_rgb(hex) for hex in RGB2SHORT_DICT
]
334 m
= min(ary
, key
=partial(dist
, (r
, g
, b
)))
335 return RGB2SHORT_DICT
[rgb_to_hex(m
)]
338 def image_to_display(path
, start
=None, length
=None):
342 rows
, columns
= os
.popen('stty size', 'r').read().split()
346 length
= int(columns
) - 2 * start
348 i
= i
.convert('RGBA')
351 width
= min(w
, length
)
352 height
= int(float(h
) * (float(width
) / float(w
)))
354 i
= i
.resize((width
, height
), Image
.BICUBIC
)
355 height
= min(height
, IMAGE_MAX_HEIGHT
)
357 for y
in xrange(height
):
358 sys
.stdout
.write(' ' * start
)
359 for x
in xrange(width
):
360 p
= i
.getpixel((x
, y
))
362 pixel_print(rgb2short(r
, g
, b
))
363 sys
.stdout
.write('\n')
367 For direct using purpose
369 if __name__
== '__main__':
370 image_to_display(sys
.argv
[1])