Effects.py (view raw)
1from PIL import Image, ImageDraw, ImageFont
2import textwrap, os
3
4IMPACT_FONT_FILE = os.path.join("fonts", "impact.ttf")
5BASE_WIDTH = 1200
6LETTER_SPACING = 9
7LINE_SPACING = 10
8FILL = (255, 255, 255)
9STROKE_WIDTH = 9
10STROKE_FILL = (0, 0, 0)
11FONT_BASE = 100
12MARGIN = 10
13
14def _draw_tt_bt(text, img, bottom=False):
15 split_caption = textwrap.wrap(text.upper(), width=20)
16 if split_caption == []:
17 return
18 font_size = FONT_BASE + 10 if len(split_caption) <= 1 else FONT_BASE
19 font = ImageFont.truetype(font=IMPACT_FONT_FILE, size=font_size)
20 img_width, img_height = img.size
21
22 d = ImageDraw.Draw(img)
23 txt_height = d.textbbox((0, 0), split_caption[0], font=font)[3]
24
25 if bottom:
26 factor = -1
27 split_caption.reverse()
28 y = (img_height - (img_height / MARGIN)) - (txt_height / 2)
29 else:
30 factor = 1
31 y = ((img_height / MARGIN)) - (txt_height / 1.5)
32
33 for line in split_caption:
34 txt_width = d.textbbox((0, 0), line, font=font)[2]
35
36 x = (img_width - txt_width - (len(line) * LETTER_SPACING))/2
37
38 for i in range(len(line)):
39 char = line[i]
40 width = font.getlength(char)
41 d.text((x, y), char, fill=FILL, stroke_width=STROKE_WIDTH, font=font, stroke_fill=STROKE_FILL)
42 x += width + LETTER_SPACING
43
44 y = y + (txt_height + LINE_SPACING) * factor
45
46def tt_bt_effect(text, img):
47 lines = [x for x in text.split("\n") if x]
48
49 tt = lines[0] if len(lines) > 0 else None
50 bt = lines[1] if len(lines) > 1 else None
51
52 img = img.resize((BASE_WIDTH, int(img.size[1] * float(BASE_WIDTH / img.size[0]))))
53
54 if tt is None and bt is None:
55 return img
56
57 if (tt is not None):
58 _draw_tt_bt(tt, img)
59 if (bt is not None):
60 _draw_tt_bt(bt, img, bottom=True)
61
62 h_size = int(float(img.size[1]) * (BASE_WIDTH/2) / img.size[0])
63 img = img.resize((int(BASE_WIDTH/2), h_size))
64
65 if img.mode in ("RGBA", "P"):
66 img = img.convert("RGB")
67
68 return img
69
70def image_test():
71 image = Image.open("image.jpg")
72 #image, url = get_random_image()
73
74 res = tt_bt_effect("top text\nbottom text", image)
75 res.save('./output.jpg', optimize=True, quality=80)
76
77 print("Image test successful")
78
79if __name__ == "__main__":
80 #main()
81 image_test()