from PIL import Image, ImageDraw, ImageFont import requests from resizeimage import resizeimage OUTPUT_RESOLUTION = (1280, 720) TITLE_FONT = ImageFont.truetype("Roboto-Regular.ttf", 92) TAGS_FONT = ImageFont.truetype("RobotoMono-Regular.ttf", 40) FOOTER_FONT = ImageFont.truetype("RobotoMono-Regular.ttf", 25) TITLE_PADDING = 75 TITLE = "Accessing Tailscale whilst using Mullvad" TAGS = "#linux #containers #foobar" def get_text_width(text, font): return draw.multiline_textbbox((0, 0), text=text, font=font)[2] def split_words_for_length(text, font, max_width): """ Copied from mkdocs-material social plugin. """ lines = [] words = [] for word in text.split(" "): combine = " ".join(words + [word]) width = get_text_width(combine, font=font) if not words or width <= max_width: words.append(word) else: lines.append(words) words = [word] lines.append(words) return [" ".join(line) for line in lines] print("Requesting") bg_image_request = requests.get( "https://images.unsplash.com/photo-1544957264-d520d519a8d5?crop=entropy&cs=srgb&fm=jpg&ixid=M3wzNjExNzd8MHwxfGFsbHx8fHx8fHx8fDE3MzMzNTY4MjB8&ixlib=rb-4.0.3&q=85", stream=True, ) bg_image_request.raise_for_status() print("Opening") bg_image = Image.open(bg_image_request.raw) print("Resizing") bg_image = resizeimage.resize_cover(bg_image, OUTPUT_RESOLUTION) draw = ImageDraw.Draw(bg_image, "RGBA") print("Drawing title") draw.rectangle([(0, 0), OUTPUT_RESOLUTION], fill=(0, 0, 0, int(255 * 0.66))) title_lines = split_words_for_length( TITLE, TITLE_FONT, OUTPUT_RESOLUTION[0] - (TITLE_PADDING * 2) ) draw.text( (OUTPUT_RESOLUTION[0] / 2, OUTPUT_RESOLUTION[1] / 2), text="\n".join(title_lines), font=TITLE_FONT, fill="white", anchor="mm", align="center", ) print("Drawing tags") title_top = (OUTPUT_RESOLUTION[1] / 2) - (TITLE_FONT.size * len(title_lines) / 2) tags_lines = split_words_for_length( TAGS, TAGS_FONT, OUTPUT_RESOLUTION[0] - (TITLE_PADDING * 2) ) draw.text( (OUTPUT_RESOLUTION[0] / 2, title_top - (TAGS_FONT.size * 1.25)), text=TAGS, font=TAGS_FONT, fill="#e85537", anchor="mm", align="center", ) print("Drawing footer") draw.rectangle( [(0, OUTPUT_RESOLUTION[1] - 50), OUTPUT_RESOLUTION], fill=(0, 0, 0, int(255 * 0.5)) ) draw.text( (25, OUTPUT_RESOLUTION[1] - 25), text="theorangeone.net", font=FOOTER_FONT, fill="#e85537", anchor="lm", align="center", ) draw.text( (OUTPUT_RESOLUTION[0] - 25, OUTPUT_RESOLUTION[1] - 25), text="2024-01-01", font=FOOTER_FONT, fill="white", anchor="rm", align="right", ) print("Saving") with open(f"image.{bg_image.format.lower()}", "wb") as f: bg_image.save(f, optimize=True)