Files
pigway-frame-flow/pigway_frame_flow/renderers/photo_caption.py
T

30 lines
1.1 KiB
Python

"""Native frame image with a separate, high-contrast caption area."""
from io import BytesIO
from PIL import Image, ImageDraw
from pigway_frame_flow.renderers.images import convert
def render_captioned_photo(data, caption, font_loader, fit="contain", profile="color"):
photo_data = convert(data, fit, profile, size=(1200, 1280))
canvas = Image.new("RGB", (1200, 1600), "white")
with Image.open(BytesIO(photo_data)) as photo:
canvas.paste(photo, (0, 0))
draw = ImageDraw.Draw(canvas)
lines = [(caption["title"], 1320, 52), (caption["date"], 1410, 40)]
if caption.get("place"):
lines.append((caption["place"], 1480, 38))
for text, y, size in lines:
font = font_loader(size)
while size > 24 and draw.textlength(text, font=font) > 1080:
size -= 2
font = font_loader(size)
while draw.textlength(text, font=font) > 1080 and text:
text = text[:-2] + "…"
draw.text((600, y), text, font=font, fill="black", anchor="mt")
out = BytesIO()
canvas.save(out, "JPEG", quality=93, optimize=True)
return out.getvalue()