-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomputer_text_generator.py
More file actions
75 lines (57 loc) · 2.65 KB
/
computer_text_generator.py
File metadata and controls
75 lines (57 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import random
from PIL import Image, ImageColor, ImageFont, ImageDraw, ImageFilter
def generate(text, font, text_color, font_size, orientation, space_width, fit):
if orientation == 0:
return _generate_horizontal_text(text, font, text_color, font_size, space_width, fit)
elif orientation == 1:
return _generate_vertical_text(text, font, text_color, font_size, space_width, fit)
else:
raise ValueError("Unknown orientation " + str(orientation))
def _generate_horizontal_text(text, font, text_color, font_size, space_width, fit):
image_font = ImageFont.truetype(font=font, size=font_size)
words = text.split(' ')
space_width = image_font.getsize(' ')[0] * space_width
# print('[words] --> ' + str(words))
# words_width = []
# for w in words:
# # print('[w] --> ' + str(w))
# words_width.append(image_font.getsize(w)[0])
words_width = [image_font.getsize(w)[0] for w in words]
text_width = sum(words_width) + int(space_width) * (len(words) - 1)
text_height = max([image_font.getsize(w)[1] for w in words])
txt_img = Image.new('RGBA', (text_width, text_height), (0, 0, 0, 0))
txt_draw = ImageDraw.Draw(txt_img)
colors = [ImageColor.getrgb(c) for c in text_color.split(',')]
c1, c2 = colors[0], colors[-1]
fill = (
random.randint(min(c1[0], c2[0]), max(c1[0], c2[0])),
random.randint(min(c1[1], c2[1]), max(c1[1], c2[1])),
random.randint(min(c1[2], c2[2]), max(c1[2], c2[2]))
)
for i, w in enumerate(words):
txt_draw.text((sum(words_width[0:i]) + i * int(space_width), 0), w, fill=fill, font=image_font)
if fit:
return txt_img.crop(txt_img.getbbox())
else:
return txt_img
def _generate_vertical_text(text, font, text_color, font_size, space_width, fit):
image_font = ImageFont.truetype(font=font, size=font_size)
space_height = int(image_font.getsize(' ')[1] * space_width)
char_heights = [image_font.getsize(c)[1] if c != ' ' else space_height for c in text]
text_width = max([image_font.getsize(c)[0] for c in text])
text_height = sum(char_heights)
txt_img = Image.new('RGBA', (text_width, text_height), (0, 0, 0, 0))
txt_draw = ImageDraw.Draw(txt_img)
colors = [ImageColor.getrgb(c) for c in text_color.split(',')]
c1, c2 = colors[0], colors[-1]
fill = (
random.randint(c1[0], c2[0]),
random.randint(c1[1], c2[1]),
random.randint(c1[2], c2[2])
)
for i, c in enumerate(text):
txt_draw.text((0, sum(char_heights[0:i])), c, fill=fill, font=image_font)
if fit:
return txt_img.crop(txt_img.getbbox())
else:
return txt_img