From eb1e146da92742757746b75c88ebb02aefa383b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Gr=C3=B6ger?= Date: Mon, 22 Mar 2021 23:17:26 +0100 Subject: [PATCH] [utils] picture creator --- flaschengeist/utils/picture.py | 38 ++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 flaschengeist/utils/picture.py diff --git a/flaschengeist/utils/picture.py b/flaschengeist/utils/picture.py new file mode 100644 index 0000000..968e764 --- /dev/null +++ b/flaschengeist/utils/picture.py @@ -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