Files
Font-Guessing-Game/font_game/images.py
Nikolaj bcffb44393 nesau
2022-01-14 10:40:45 +01:00

45 lines
1.1 KiB
Python

import os
from PIL import Image, ImageFont, ImageDraw
import lorem
from font_game import gen_id, 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 = gen_id()
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))