|
from PIL import Image, ImageDraw, ImageFont |
|
|
|
|
|
def print_text_on_image_centered(image, text, color="black"): |
|
|
|
draw = ImageDraw.Draw(image) |
|
|
|
|
|
|
|
font_size = 30 |
|
font = ImageFont.load_default().font_variant(size=font_size) |
|
|
|
|
|
text_bbox = draw.textbbox((0, 0), text, font=font) |
|
text_width = text_bbox[2] - text_bbox[0] |
|
text_height = text_bbox[3] - text_bbox[1] |
|
|
|
|
|
while text_width > image.width: |
|
font_size -= 1 |
|
font = ImageFont.load_default().font_variant(size=font_size) |
|
text_bbox = draw.textbbox((0, 0), text, font=font) |
|
text_width = text_bbox[2] - text_bbox[0] |
|
|
|
|
|
text_x = (image.width - text_width) / 2 |
|
text_y = (image.height - text_height) / 2 |
|
|
|
|
|
draw.text((text_x, text_y), text, font=font, fill=color) |
|
return image |
|
|
|
|
|
|
|
def create_background_image(width, height, color="white"): |
|
return Image.new("RGB", (width, height), color) |
|
|
|
|