import os import time from PIL import Image, ImageFont, ImageDraw import lorem from font_game import base64, IMAGE_SIZE, IMAGE_BACKGROUND, MARGINS, FONT_COLOR def gen_image(font: ImageFont.ImageFont) -> str: img = Image.new("RGB", IMAGE_SIZE, IMAGE_BACKGROUND) drawer = ImageDraw.Draw(img) text_width = IMAGE_SIZE[0] - 2 * MARGINS text = lorem.sentence() text_list = [] line = "" for word in text.split(" "): if drawer.textsize(line + word, font)[0] > text_width: text_list.append(line) line = "" else: line += word + " " text_list.append(line) drawer.text( (MARGINS, MARGINS), '\n'.join(text_list), FONT_COLOR, font, spacing=30 ) filename = base64(int(time.time() * 10000) % 0xffffff) path = f"static/images/{filename}.png" new_size = (IMAGE_SIZE[0] // 2, IMAGE_SIZE[1] // 2) img = img.resize(new_size, resample=Image.ANTIALIAS) img.save(path) return filename def purge_images(): for root, _, files in os.walk("static/images"): for file in files: os.remove(os.path.join(root, file))