2 from PIL import Image, ImageDraw, ImageFont
5 def drawbox(img, d, context, get_font_path):
6 for version in d['versions']:
7 if draw_version(img, version, context, get_font_path):
11 def split_to_lines(text, draw, font, max_width):
16 new_words.append(words.pop(0))
17 while len(new_words[-1]) == 1 and words:
18 new_words.append(words.pop(0))
19 new_words = ' '.join(new_words)
20 new_line = ' '.join([current, new_words]).strip()
21 width = draw.textsize(new_line, font=font)[0]
31 def draw_version(img, d, context, get_font_path):
32 # todo: do this in a subimg
36 img.size[0] - d.get('x', 0),
37 d.get('max-height', img.size[1] - d.get('y', 0)),
41 draw = ImageDraw.Draw(newimg)
43 for item in d['items']:
45 cursor += item['vskip']
46 text = item['text'].format(**context)
47 if item.get('uppercase'):
49 font = ImageFont.truetype(get_font_path(item['font-family']), item['font-size'])
50 max_width = item.get('max-width', newimg.size[0])
52 for line in split_to_lines(text, draw, font, max_width):
53 realheight = draw.textsize(line, font=font)[1]
54 if cursor + realheight > newimg.size[1]:
56 draw.text((0, cursor), line, font=font, fill=item.get('color'))
57 cursor += item['line-height']
59 img.paste(newimg, (d.get('x', 0), d.get('y', 0)), newimg)
63 def create_thumbnail(background_path, defn, context, get_font_path):
64 img = Image.open(background_path)
66 for boxdef in d['boxes']:
67 drawbox(img, boxdef, context, get_font_path)