2 from PIL import Image, ImageDraw, ImageFont
5 def split_to_lines(text, draw, font, max_width):
10 new_words.append(words.pop(0))
11 while len(new_words[-1]) == 1 and words:
12 new_words.append(words.pop(0))
13 new_words = ' '.join(new_words)
14 new_line = ' '.join([current, new_words]).strip()
15 width = draw.textsize(new_line, font=font)[0]
25 def draw_box(img, d, context, get_font_path, scale):
29 img.size[0] - d.get('x', 0),
30 d.get('max-height', img.size[1] - d.get('y', 0)),
34 draw = ImageDraw.Draw(newimg)
36 for item in d['items']:
38 cursor += int(round(item['vskip'] * scale))
39 text = item['text'].format(**context)
42 if item.get('uppercase'):
44 font = ImageFont.truetype(
45 get_font_path(item['font-family']),
46 int(round(item['font-size'] * scale)),
47 layout_engine=ImageFont.LAYOUT_BASIC
49 max_width = item.get('max-width', newimg.size[0])
51 for line in split_to_lines(text, draw, font, max_width):
52 realheight = draw.textsize(line, font=font)[1]
53 if cursor + realheight > newimg.size[1]:
55 draw.text((0, cursor), line, font=font, fill=item.get('color'))
56 cursor += int(round(item['line-height'] * scale))
58 img.paste(newimg, (d.get('x', 0), d.get('y', 0)), newimg)
62 def draw_box_with_scaling(img, d, context, get_font_path):
65 if draw_box(img, d, context, get_font_path, scale):
71 def create_thumbnail(background_path, defn, context, get_font_path):
72 img = Image.open(background_path)
74 for boxdef in d['boxes']:
75 if not draw_box_with_scaling(img, boxdef, context, get_font_path):