-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_text.py
50 lines (32 loc) · 1.35 KB
/
add_text.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
from PIL import Image, ImageDraw, ImageFont
def add_text_to_panel(text, panel_image):
text_image = generate_text_image(text)
result_image = Image.new('RGB', (panel_image.width, panel_image.height + text_image.height))
result_image.paste(panel_image, (0, 0))
result_image.paste(text_image, (0, panel_image.height))
return result_image
def textsize(text, font):
im = Image.new(mode="P", size=(0, 0))
draw = ImageDraw.Draw(im)
_, _, width, height = draw.textbbox((0, 0), text=text, font=font)
return width, height
def generate_text_image(text):
# Define image dimensions
width = 1024
height = 128
# Create a white background image
image = Image.new('RGB', (width, height), color='white')
# Create a drawing context
draw = ImageDraw.Draw(image)
# Choose a font (Pillow's default font)
font = ImageFont.truetype(font="manga-temple.ttf", size=30)
# # Calculate text size
text_width, text_height = textsize(text, font)
# Calculate the position to center the text horizontally and vertically
x = (width - text_width) // 2
y = (height - text_height) // 2
# Define text color (black in this example)
text_color = (0, 0, 0)
# Add text to the image
draw.text((x, y), text, fill=text_color, font=font)
return image