-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathfinal.py
90 lines (69 loc) · 2.41 KB
/
final.py
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
img = Image.open("image.jpg")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("impact.ttf", 42)
def drawTextWithOutline(text, x, y):
draw.text((x-2, y-2), text,(0,0,0),font=font)
draw.text((x+2, y-2), text,(0,0,0),font=font)
draw.text((x+2, y+2), text,(0,0,0),font=font)
draw.text((x-2, y+2), text,(0,0,0),font=font)
draw.text((x, y), text, (255,255,255), font=font)
return
def drawText(text, pos):
text = text.upper()
w, h = draw.textsize(text, font) # measure the size the text will take
lineCount = 1
if w > img.width:
lineCount = int(round((w / img.width) + 1))
print("lineCount: {}".format(lineCount))
lines = []
if lineCount > 1:
lastCut = 0
isLast = False
for i in range(0,lineCount):
if lastCut == 0:
cut = (len(text) / lineCount) * i
else:
cut = lastCut
if i < lineCount-1:
nextCut = (len(text) / lineCount) * (i+1)
else:
nextCut = len(text)
isLast = True
print("cut: {} -> {}".format(cut, nextCut))
# make sure we don't cut words in half
if nextCut == len(text) or text[nextCut] == " ":
print("may cut")
else:
print("may not cut")
while text[nextCut] != " ":
nextCut += 1
print("new cut: {}".format(nextCut))
line = text[cut:nextCut].strip()
# is line still fitting ?
w, h = draw.textsize(line, font)
if not isLast and w > img.width:
print("overshot")
nextCut -= 1
while text[nextCut] != " ":
nextCut -= 1
print("new cut: {}".format(nextCut))
lastCut = nextCut
lines.append(text[cut:nextCut].strip())
else:
lines.append(text)
print(lines)
lastY = -h
if pos == "bottom":
lastY = img.height - h * (lineCount+1) - 10
for i in range(0, lineCount):
w, h = draw.textsize(lines[i], font)
x = img.width/2 - w/2
y = lastY + h
drawTextWithOutline(lines[i], x, y)
lastY = y
drawText("One does not simply", "top")
drawText("make memes great again with several lines", "bottom")
img.save("out.jpg")