Fix image uploads and reduce flyer request sizes
This commit is contained in:
+13
-3
@@ -1044,17 +1044,27 @@ def save_image(upload: UploadFile, destination_dir: str, url_prefix: str):
|
||||
if image.width * image.height > MAX_IMAGE_PIXELS:
|
||||
raise ValueError("Bildauflösung zu groß")
|
||||
image.thumbnail((2400, 2400))
|
||||
has_alpha = image.mode in {"RGBA", "LA"} or (
|
||||
image.mode == "P" and "transparency" in image.info
|
||||
)
|
||||
if image.mode not in {"RGB", "RGBA"}:
|
||||
image = image.convert("RGBA" if "transparency" in image.info else "RGB")
|
||||
image = image.convert("RGBA" if has_alpha else "RGB")
|
||||
output = BytesIO()
|
||||
image.save(output, format="WEBP", quality=88, method=6)
|
||||
# Nicht jedes Browser-/Proxy-Setup verarbeitet serverseitig
|
||||
# erzeugte WebP-Dateien zuverlässig. Nach der Validierung bleiben
|
||||
# transparente Bilder PNG, normale Bilder werden als JPEG gespeichert.
|
||||
output_format = "PNG" if image.mode == "RGBA" else "JPEG"
|
||||
if output_format == "PNG":
|
||||
image.save(output, format=output_format, optimize=True)
|
||||
else:
|
||||
image.save(output, format=output_format, quality=88, optimize=True)
|
||||
safe_contents = output.getvalue()
|
||||
except (ValueError, OSError, UnidentifiedImageError, Image.DecompressionBombError):
|
||||
return None, HTMLResponse(
|
||||
"Die Datei ist kein gültiges oder unterstütztes Bild.", status_code=400
|
||||
)
|
||||
|
||||
filename = str(uuid.uuid4()) + ".webp"
|
||||
filename = str(uuid.uuid4()) + (".png" if output_format == "PNG" else ".jpg")
|
||||
destination = os.path.join(destination_dir, filename)
|
||||
with open(destination, "wb") as file:
|
||||
file.write(safe_contents)
|
||||
|
||||
Reference in New Issue
Block a user