48 lines
1.3 KiB
Python
48 lines
1.3 KiB
Python
import os
|
|
import random
|
|
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:
|
|
image_mult = random.uniform(0.8,1.2)
|
|
image_size = (int(IMAGE_SIZE[0]*image_mult), int(IMAGE_SIZE[1]*image_mult))
|
|
img = Image.new("RGB", image_size, IMAGE_BACKGROUND)
|
|
drawer = ImageDraw.Draw(img)
|
|
text_width = int((IMAGE_SIZE[0] - 2 * MARGINS)*image_mult)
|
|
text = lorem.sentence()
|
|
text_list = []
|
|
line = ""
|
|
for word in text.split(" "):
|
|
if drawer.textlength(line + word, font) > text_width:
|
|
text_list.append(line)
|
|
line = ""
|
|
else:
|
|
line += word + " "
|
|
|
|
text_list.append(line)
|
|
|
|
drawer.text(
|
|
(int(MARGINS*image_mult), int(MARGINS*image_mult)),
|
|
'\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)
|
|
|
|
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))
|