46 lines
1.6 KiB
Python
46 lines
1.6 KiB
Python
"""Bounded child process for the CPU-intensive image conversion."""
|
|
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from PIL import Image, ImageOps, UnidentifiedImageError
|
|
|
|
from attachments import MAX_PIXELS
|
|
|
|
|
|
def fit(image, limit):
|
|
longest = max(image.size)
|
|
if longest <= limit:
|
|
return image
|
|
size = tuple(max(1, side * limit // longest) for side in image.size)
|
|
return image.resize(size, Image.Resampling.LANCZOS)
|
|
|
|
|
|
def convert(root):
|
|
try:
|
|
with Image.open(root / "source") as source:
|
|
if source.width * source.height > MAX_PIXELS or source.format not in ("PNG", "JPEG"):
|
|
return 2
|
|
with ImageOps.exif_transpose(source).convert("RGBA") as image:
|
|
rgb = Image.new("RGB", image.size, "white")
|
|
rgb.paste(image, mask=image.getchannel("A"))
|
|
except (UnidentifiedImageError, Image.DecompressionBombError, SyntaxError, OSError):
|
|
return 2
|
|
outputs = [
|
|
("thumbnail", fit(rgb, 256), "JPEG", "image/jpeg", 85),
|
|
("crop", ImageOps.fit(rgb, (128, 128), Image.Resampling.LANCZOS), "JPEG", "image/jpeg", 85),
|
|
("optimized", fit(rgb, 1280), "WEBP", "image/webp", 82),
|
|
]
|
|
descriptors = []
|
|
for name, image, format_name, mime, quality in outputs:
|
|
image.info.clear()
|
|
image.save(root / name, format=format_name, quality=quality)
|
|
descriptors.append({"name": name, "content_type": mime, "width": image.width, "height": image.height})
|
|
(root / "variants.json").write_text(json.dumps(descriptors), encoding="utf-8")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(convert(Path(sys.argv[1])))
|