terom@79: """ terom@79: Use of PIL to render the image formatting stuff terom@79: """ terom@79: terom@79: from PIL import Image, ImageDraw, ImageFont terom@79: terom@79: from cStringIO import StringIO terom@79: terom@79: class PILImageFormatter (object) : terom@79: """ terom@79: Implements the basic image-rendering operations on top of format_txt terom@79: """ terom@79: terom@79: # the font we load terom@79: font = None terom@79: terom@79: def _load_font (self) : terom@79: """ terom@79: Use the configured img_ttf_path for a TrueType font, or a default one terom@79: """ terom@79: terom@79: if self.font : terom@79: pass terom@79: terom@79: elif self.img_ttf_path : terom@79: # load truetype with configured size terom@79: self.font = ImageFont.truetype(self.img_ttf_path, self.img_font_size) terom@79: terom@79: else : terom@79: # default terom@79: self.font = ImageFont.load_default() terom@79: terom@79: return self.font terom@79: terom@79: def format_png (self, lines, **kwargs) : terom@79: # load font terom@79: font = self._load_font() terom@79: terom@79: # build list of plain-text line data terom@79: lines = list(data for line, data in self.format_txt(lines, **kwargs)) terom@79: terom@79: # lines sizes terom@79: line_sizes = [font.getsize(line) for line in lines] terom@79: terom@79: # figure out how wide/high the image will be terom@79: width = max(width for width, height in line_sizes) terom@79: height = sum(height for width, height in line_sizes) terom@79: terom@79: # create new B/W image terom@79: img = Image.new('L', (width, height), 0xff) terom@79: terom@79: # drawer terom@79: draw = ImageDraw.Draw(img) terom@79: terom@79: # starting offset terom@79: offset_y = 0 terom@79: terom@79: # draw the lines terom@79: for line, (width, height) in zip(lines, line_sizes) : terom@79: # draw terom@79: draw.text((0, offset_y), line, font=font) terom@79: terom@79: # next offset terom@79: offset_y += height terom@79: terom@79: # output buffer terom@79: buf = StringIO() terom@79: terom@79: # save terom@79: img.save(buf, 'png') terom@79: terom@79: # return data terom@79: return buf.getvalue() terom@79: