File: converter.py

package info (click to toggle)
libsixel 1.10.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,496 kB
  • sloc: ansic: 23,873; cpp: 1,227; python: 497; sh: 303; xml: 271; makefile: 50; ruby: 31; perl: 26
file content (45 lines) | stat: -rwxr-xr-x 1,438 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python3

import sys
from libsixel import *
from PIL import Image
from io import BytesIO

s = BytesIO()

file = sys.argv[1]
image = Image.open(file)
width, height = image.size
try:
    data = image.tobytes()
except NotImplementedError:
    data = image.tostring()
output = sixel_output_new(lambda data, s: s.write(data), s)

try:
    if image.mode == 'RGBA':
        dither = sixel_dither_new(256)
        sixel_dither_initialize(dither, data, width, height, SIXEL_PIXELFORMAT_RGBA8888)
    elif image.mode == 'RGB':
        dither = sixel_dither_new(256)
        sixel_dither_initialize(dither, data, width, height, SIXEL_PIXELFORMAT_RGB888)
    elif image.mode == 'P':
        palette = image.getpalette()
        dither = sixel_dither_new(256)
        sixel_dither_set_palette(dither, palette)
        sixel_dither_set_pixelformat(dither, SIXEL_PIXELFORMAT_PAL8)
    elif image.mode == 'L':
        dither = sixel_dither_get(SIXEL_BUILTIN_G8)
        sixel_dither_set_pixelformat(dither, SIXEL_PIXELFORMAT_G8)
    elif image.mode == '1':
        dither = sixel_dither_get(SIXEL_BUILTIN_G1)
        sixel_dither_set_pixelformat(dither, SIXEL_PIXELFORMAT_G1)
    else:
        raise RuntimeError('unexpected image mode')
    try:
        sixel_encode(data, width, height, 1, dither, output)
        print(s.getvalue().decode('ascii'))
    finally:
        sixel_dither_unref(dither)
finally:
    sixel_output_unref(output)