source: libcaca/trunk/python/examples/img2txt.py @ 4706

Last change on this file since 4706 was 4706, checked in by Alex Foulon, 8 years ago
  • Add example: port of img2txt with python bindings.
  • Property svn:executable set to *
File size: 6.4 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#
4# img2txt       image to text converter
5# Copyright (c) 2010 Alex Foulon <alxf@lavabit.com>
6#
7# This file is a Python port of "src/img2txt.c"
8# which is:
9# Copyright (c) 2006 Sam Hocevar <sam@hocevar.net>
10#               2007 Jean-Yves Lamoureux <jylam@lnxscene.org>
11#               All Rights Reserverd
12#
13# This library is free software. It comes without any warranty, to
14# the extent permitted by applicable law. You can redistribute it
15# and/or modify it under the terms of the Do What The Fuck You Want
16# To Public License, Version 2, as published by Sam Hocevar. See
17# http://sam.zoy.org/wtfpl/COPYING for more details.
18#
19
20import getopt
21import os
22import sys
23
24import caca
25from caca.canvas import Canvas, CanvasError
26from caca.dither import Dither, DitherError
27
28RMASK = 0x00ff0000
29GMASK = 0x0000ff00
30BMASK = 0x000000ff
31AMASK = 0x00000000
32BPP = 32
33DEPTH = 4
34
35HELP_MSG = """\
36Usage: %s [OPTIONS]... <IMAGE>
37Convert IMAGE to any text based available format.
38Example: %s -w 80 -f ansi ./caca.png
39
40Options:
41  -h, --help                      This help
42  -v, --version                   Version of the program
43  -W, --width=WIDTH               Width of resulting image
44  -H, --height=HEIGHT             Height of resulting image
45  -x, --font-width=WIDTH          Width of output font
46  -y, --font-height=HEIGHT        Height of output font
47  -b, --brightness=BRIGHTNESS     Brightness of resulting image
48  -c, --contrast=CONTRAST         Contrast of resulting image
49  -g, --gamma=GAMMA               Gamma of resulting image
50  -d, --dither=DITHER             Dithering algorithm to use
51  -f, --format=FORMAT             Format of the resulting image
52  -C, --charset=CHARSET           Charset of the resulting image
53
54DITHER list:
55  - none: no dithering
56  - ordered2: 2x2 ordered dithering
57  - ordered4: 4x4 ordered dithering
58  - ordered8: 8x8 orederd dithering
59  - random: random dithering
60  - fstein: Floyd-Steinberg dithering
61
62FORMAT list:
63  - caca: native libcaca format
64  - ansi: ANSI
65  - utf8: UTF-8 with ANSI escape codes
66  - utf8cr: UTF-8 with ANSI escape codes and MS-DOS \\r
67  - html: HTML
68  - html3: backwards-compatible HTML
69  - bbfr: BBCode (French)
70  - irc: IRC with mIRC colours
71  - ps: PostScript document
72  - svg: SVG vector image
73  - tga: TGA image
74  - troff: troff source
75
76CHARSET list:
77  - ascii: use only ascii character
78  - shades: use unicode character
79  - blocks: use unicode quarter-cell combinations
80""" % (os.path.basename(sys.argv[0]), os.path.basename(sys.argv[0]))
81
82VERSION_MSG="""\
83img2txt Copyright 2006-2007 Sam Hocevar and Jean-Yves Lamoureux
84        Copyright 2010      Alex Foulon
85Internet: <sam@hocevar.net> <jylam@lnxscene.org>
86          <alxf@lavabit.com> version: %s
87
88img2txt, along with its documentation, may be freely copied and distributed.
89
90The latest version of img2txt is available from the web site,
91        http://caca.zoy.org/wiki/libcaca in the libcaca package.
92""" % caca.get_version()
93
94def main():
95    """ Main script function.
96    """
97
98    #init options vars
99    width = None
100    height = None
101    font_width = 6
102    font_height = 10
103    brightness = None
104    contrast = None
105    gamma = None
106    ditalgo = None
107    exformat = "ansi"
108    charset = None
109
110    #define long and short options
111    shortopts = "hvW:H:x:y:b:c:g:d:f:C:"
112    longopts = [
113        "help",
114        "version",
115        "width=",
116        "height=",
117        "font-width=",
118        "font-height=",
119        "brightness=",
120        "contrast=",
121        "gamma=",
122        "dither=",
123        "format=",
124        "charset=",
125    ]
126
127    #parse command line
128    try:
129        opts, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
130    except getopt.GetoptError, err:
131        sys.stderr.write("%s\n" % str(err))
132        sys.exit(127)
133
134    for o, a in opts:
135        if o in ('-h', '--help'):
136            sys.stdout.write(HELP_MSG)
137            sys.exit(0)
138        elif o in ('-v', '--version'):
139            sys.stdout.write("%s\n" % VERSION_MSG)
140            sys.exit(0)
141        elif o in ('-W', '--width'):
142            width = int(a)
143        elif o in ('-H', '--height'):
144            height = int(a)
145        elif o in ('-x', '--font-width'):
146            font_width = int(a)
147        elif o in ('-y', '--font-height'):
148            font_height = int(a)
149        elif o in ('-b', '--brightness'):
150            brightness = float(a)
151        elif o in ('-c', '--contrast'):
152            contrast = float(a)
153        elif o in ('-g', '--gamma'):
154            gamma = float(a)
155        elif o in ('-d', '--dither'):
156            ditalgo = a
157        elif o in ('-f', '--format'):
158            exformat = a
159        elif o in ('-C', '--charset'):
160            charset = a
161
162    if not args:
163        sys.stderr.write("%s: Missing argument...\n" % os.path.basename(sys.argv[0]))
164        sys.exit(127)
165    else:
166        try:
167            img = Image.open(args[0])
168            img.load()
169        except IOError, err:
170            sys.stderr.write("%s\n" % err)
171            sys.exit(127)
172
173    if not width and not height:
174        width = 60
175        height = width * img.size[1] * font_width / img.size[0] / font_height
176    elif width and not height:
177        height = width * img.size[1] * font_width / img.size[0] / font_height
178    elif not width and height:
179        width = height * img.size[0] * font_height / img.size[1] / font_width
180
181    #init canvas
182    try:
183        cv = Canvas(width, height)
184    except CanvasError, err:
185        sys.stderr.write("%s\n" % err)
186        sys.exit(127)
187
188    cv.set_color_ansi(caca.COLOR_DEFAULT, caca.COLOR_TRANSPARENT)
189
190    #init dither
191    try:
192        dit = Dither(BPP, img.size[0], img.size[1], DEPTH * img.size[0],
193                      RMASK, GMASK, BMASK, AMASK)
194    except DitherError, err:
195        sys.stderr.write("%s\n" % err)
196        sys.exit(127)
197
198    #set dither algorithm
199    if ditalgo:
200        dit.set_algorithm(ditalgo)
201
202    #set brightness
203    if brightness:
204        dit.set_brightness(brightness)
205
206    #set gamma
207    if gamma:
208        dit.set_gamma(gamma)
209
210    #set contrast
211    if contrast:
212        dit.set_contrast(contrast)
213
214    #set charset
215    if charset:
216        dit.set_charset(charset)
217
218    #create dither
219    dit.bitmap(cv, 0, 0, width, height, img.tostring())
220
221    #print export to screen
222    sys.stdout.write("%s" % cv.export_to_memory(exformat))
223
224if __name__ == "__main__":
225    #Import PIL package
226    try:
227        from PIL import Image
228    except ImportError, err:
229        sys.stderr.write("You need to install PIL module !\n")
230        sys.exit(2)
231
232    main()
233
Note: See TracBrowser for help on using the repository browser.