[utils] picture creator

This commit is contained in:
Tim Gröger 2021-03-22 23:17:26 +01:00
parent b98bae337d
commit eb1e146da9
1 changed files with 38 additions and 0 deletions

View File

@ -0,0 +1,38 @@
import os, sys
from PIL import Image
from flask import Response
from werkzeug.exceptions import BadRequest
thumbnail_sizes = ((32, 32), (64, 64), (128, 128), (256, 256), (512, 512))
def save_picture(picture, path):
if not picture.mimetype.startswith("image/"):
raise BadRequest
os.makedirs(path, exist_ok=True)
file_type = picture.mimetype.replace("image/", "")
filename = f"{path}/drink"
with open(f"{filename}.{file_type}", "wb") as file:
file.write(picture.binary)
image = Image.open(f"{filename}.{file_type}")
if file_type != "png":
image.save(f"{filename}.png", "PNG")
os.remove(f"{filename}.{file_type}")
image.show()
for thumbnail_size in thumbnail_sizes:
work_image = image.copy()
work_image.thumbnail(thumbnail_size)
work_image.save(f"{filename}-{thumbnail_size[0]}.png", "PNG")
def get_picture(path, size=None):
if size:
with open(f"{path}/drink-{size}.png", "rb") as file:
image = file.read()
else:
with open(f"{path}/drink.png", "rb") as file:
image = file.read()
response = Response(image, mimetype="image/png")
response.add_etag()
return response