Faster sniffing
[mediagoblin.git] / mediagoblin / media_types / ascii / asciitoimage.py
CommitLineData
a246ccca 1# GNU MediaGoblin -- federated, autonomous media hosting
cf29e8a8 2# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
a246ccca
JW
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU Affero General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU Affero General Public License for more details.
13#
14# You should have received a copy of the GNU Affero General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17import Image
18import ImageFont
19import ImageDraw
20import logging
21import pkg_resources
22import os
23
24_log = logging.getLogger(__name__)
25
26class AsciiToImage(object):
27 '''
28 Converter of ASCII art into image files, preserving whitespace
29
30 kwargs:
31 - font: Path to font file
32 default: fonts/Inconsolata.otf
33 - font_size: Font size, ``int``
34 default: 11
35 '''
36
37 # Font file path
38 _font = None
39
40 _font_size = 11
41
42 # ImageFont instance
43 _if = None
44
45 # ImageFont
46 _if_dims = None
47
48 # Image instance
49 _im = None
50
51 def __init__(self, **kw):
52 if kw.get('font'):
53 self._font = kw.get('font')
54 else:
55 self._font = pkg_resources.resource_filename(
56 'mediagoblin.media_types.ascii',
57 os.path.join('fonts', 'Inconsolata.otf'))
58
59 if kw.get('font_size'):
60 self._font_size = kw.get('font_size')
61
a246ccca
JW
62 self._if = ImageFont.truetype(
63 self._font,
010d28b4
JW
64 self._font_size,
65 encoding='unic')
a246ccca 66
64da09e8
JW
67 _log.info('Font set to {0}, size {1}'.format(
68 self._font,
69 self._font_size))
70
a246ccca
JW
71 # ,-,-^-'-^'^-^'^-'^-.
72 # ( I am a wall socket )Oo, ___
73 # `-.,.-.,.-.-.,.-.--' ' `
74 # Get the size, in pixels of the '.' character
75 self._if_dims = self._if.getsize('.')
76 # `---'
77
78 def convert(self, text, destination):
79 # TODO: Detect if text is a file-like, if so, act accordingly
80 im = self._create_image(text)
81
82 # PIL's Image.save will handle both file-likes and paths
83 if im.save(destination):
84 _log.info('Saved image in {0}'.format(
85 destination))
86
87 def _create_image(self, text):
88 '''
89 Write characters to a PIL image canvas.
90
91 TODO:
92 - Character set detection and decoding,
93 http://pypi.python.org/pypi/chardet
94 '''
64da09e8 95 _log.debug('Drawing image')
010d28b4
JW
96 # Convert the input from str to unicode
97 text = text.decode('utf-8')
98
a246ccca
JW
99 # TODO: Account for alternative line endings
100 lines = text.split('\n')
101
102 line_lengths = [len(i) for i in lines]
103
104 # Calculate destination size based on text input and character size
105 im_dims = (
106 max(line_lengths) * self._if_dims[0],
107 len(line_lengths) * self._if_dims[1])
108
109 _log.info('Destination image dimensions will be {0}'.format(
110 im_dims))
111
112 im = Image.new(
113 'RGBA',
114 im_dims,
115 (255, 255, 255, 0))
116
117 draw = ImageDraw.Draw(im)
118
119 char_pos = [0, 0]
120
121 for line in lines:
122 line_length = len(line)
123
124 _log.debug('Writing line at {0}'.format(char_pos))
125
126 for _pos in range(0, line_length):
127 char = line[_pos]
128
129 px_pos = self._px_pos(char_pos)
130
010d28b4 131 _log.debug('Writing character "{0}" at {1} (px pos {2})'.format(
64da09e8 132 char.encode('ascii', 'replace'),
a246ccca
JW
133 char_pos,
134 px_pos))
135
136 draw.text(
137 px_pos,
138 char,
139 font=self._if,
140 fill=(0, 0, 0, 255))
141
142 char_pos[0] += 1
143
144 # Reset X position, increment Y position
145 char_pos[0] = 0
146 char_pos[1] += 1
147
148 return im
149
150 def _px_pos(self, char_pos):
151 '''
152 Helper function to calculate the pixel position based on
153 character position and character dimensions
154 '''
155 px_pos = [0, 0]
156 for index, val in zip(range(0, len(char_pos)), char_pos):
157 px_pos[index] = char_pos[index] * self._if_dims[index]
158
159 return px_pos