Files
confucius-quote-bot/image.py
T
2026-08-10 09:59:42 +03:00

118 lines
2.6 KiB
Python

from PIL import Image, ImageDraw, ImageFont
def draw_text_in_box(
image,
text,
box,
font_path,
max_font_size=100,
min_font_size=10,
fill="white",
spacing=10,
):
# another ai slop function
draw = ImageDraw.Draw(image)
x1, y1, x2, y2 = box
box_width = x2 - x1
box_height = y2 - y1
def wrap_text(text, font):
words = text.split()
lines = []
current = ""
for word in words:
test = f"{current} {word}".strip()
bbox = draw.textbbox((0, 0), test, font=font)
width = bbox[2] - bbox[0]
if width <= box_width:
current = test
else:
if current:
lines.append(current)
current = word
if current:
lines.append(current)
return lines
# Try font sizes from large to small
for font_size in range(max_font_size, min_font_size - 1, -1):
font = ImageFont.truetype(font_path, font_size)
lines = wrap_text(text, font)
# Calculate total text height
line_heights = []
for line in lines:
bbox = draw.textbbox((0, 0), line, font=font)
line_heights.append(bbox[3] - bbox[1])
text_height = sum(line_heights) + spacing * (len(lines) - 1)
if text_height <= box_height:
break
else:
raise ValueError("Text is too long even at minimum font size")
# Draw each line centered
y = y1 + (box_height - text_height) / 2
for line, line_height in zip(lines, line_heights):
bbox = draw.textbbox((0, 0), line, font=font)
line_width = bbox[2] - bbox[0]
x = x1 + (box_width - line_width) / 2
draw.text(
(x, y),
line,
font=font,
fill=fill,
)
y += line_height + spacing
def generate_quote(text:str):
# basicaly just hard-coded values
img = Image.open("assets/template.png").convert("RGB")
draw_text_in_box(
img,
text,
box=(721, 228, 1740, 951),
font_path="assets/font.ttf",
max_font_size=120,
min_font_size=20,
fill="white",
spacing=30,
)
return img
if __name__ == "__main__":
print("running test")
img = Image.open("assets/template.png").convert("RGB")
draw_text_in_box(
img,
"ЬБОПЛВОЛСМЧОЛБМСЧЮ.",
box=(721, 228, 1740, 951),
font_path="assets/font.ttf",
max_font_size=120,
min_font_size=20,
fill="white",
spacing=30,
)
img.save("output.jpg")
print("see output.jpg")