author | Tero Marttila <terom@fixme.fi> |
Tue, 10 Feb 2009 23:59:56 +0200 | |
changeset 88 | 0b8e2ba5f76f |
parent 80 | a0662cff1d9d |
child 124 | 4bc4de14f006 |
permissions | -rw-r--r-- |
79 | 1 |
""" |
2 |
Use of PIL to render the image formatting stuff |
|
3 |
""" |
|
4 |
||
5 |
from PIL import Image, ImageDraw, ImageFont |
|
6 |
||
7 |
from cStringIO import StringIO |
|
8 |
||
9 |
class PILImageFormatter (object) : |
|
10 |
""" |
|
80
a0662cff1d9d
add RSSFormatter, and link to different types from channel_last.tmpl...
Tero Marttila <terom@fixme.fi>
parents:
79
diff
changeset
|
11 |
Mixin for LogFormatter that implements the basic image-rendering operations on top of format_txt |
79 | 12 |
""" |
13 |
||
14 |
# the font we load |
|
15 |
font = None |
|
16 |
||
17 |
def _load_font (self) : |
|
18 |
""" |
|
19 |
Use the configured img_ttf_path for a TrueType font, or a default one |
|
20 |
""" |
|
21 |
||
22 |
if self.font : |
|
23 |
pass |
|
24 |
||
25 |
elif self.img_ttf_path : |
|
26 |
# load truetype with configured size |
|
27 |
self.font = ImageFont.truetype(self.img_ttf_path, self.img_font_size) |
|
28 |
||
29 |
else : |
|
30 |
# default |
|
31 |
self.font = ImageFont.load_default() |
|
32 |
||
33 |
return self.font |
|
34 |
||
35 |
def format_png (self, lines, **kwargs) : |
|
36 |
# load font |
|
37 |
font = self._load_font() |
|
38 |
||
39 |
# build list of plain-text line data |
|
40 |
lines = list(data for line, data in self.format_txt(lines, **kwargs)) |
|
41 |
||
42 |
# lines sizes |
|
43 |
line_sizes = [font.getsize(line) for line in lines] |
|
44 |
||
45 |
# figure out how wide/high the image will be |
|
46 |
width = max(width for width, height in line_sizes) |
|
47 |
height = sum(height for width, height in line_sizes) |
|
48 |
||
49 |
# create new B/W image |
|
50 |
img = Image.new('L', (width, height), 0xff) |
|
51 |
||
52 |
# drawer |
|
53 |
draw = ImageDraw.Draw(img) |
|
54 |
||
55 |
# starting offset |
|
56 |
offset_y = 0 |
|
57 |
||
58 |
# draw the lines |
|
59 |
for line, (width, height) in zip(lines, line_sizes) : |
|
60 |
# draw |
|
61 |
draw.text((0, offset_y), line, font=font) |
|
62 |
||
63 |
# next offset |
|
64 |
offset_y += height |
|
65 |
||
66 |
# output buffer |
|
67 |
buf = StringIO() |
|
68 |
||
69 |
# save |
|
70 |
img.save(buf, 'png') |
|
71 |
||
72 |
# return data |
|
73 |
return buf.getvalue() |
|
74 |