Files
mtusi2026lab5/app/transform.py
T

36 lines
1.5 KiB
Python

"""Isolated decoder: parent enforces a wall-clock timeout, container bounds RAM."""
import json
from pathlib import Path
import sys
from PIL import Image, ImageOps
from .attachments import validate_image
def transform(source, mime, destination):
with open(source, 'rb') as file:
validate_image(file, mime)
with Image.open(file) as raw:
oriented = ImageOps.exif_transpose(raw).convert('RGBA')
image = Image.new('RGB', oriented.size, 'white')
image.paste(oriented, mask=oriented.getchannel('A'))
variants = []
for name, bound, fmt in [('thumbnail',256,'JPEG'),('crop',128,'JPEG'),('optimized',1280,'WEBP')]:
if name == 'crop':
out = ImageOps.fit(image, (128,128), method=Image.Resampling.LANCZOS, centering=(.5,.5))
else:
w,h = image.size
ratio = min(1, bound/w, bound/h)
out = image.resize((max(1,int(w*ratio)),max(1,int(h*ratio))), Image.Resampling.LANCZOS)
# New RGB image removes EXIF, ICC and text metadata.
clean = Image.new('RGB', out.size)
clean.paste(out)
clean.save(Path(destination)/name, format=fmt, quality=85 if fmt=='JPEG' else 80)
variants.append({'name':name,'width':out.width,'height':out.height,
'content_type':'image/jpeg' if fmt=='JPEG' else 'image/webp'})
return variants
if __name__ == '__main__':
try:
print(json.dumps(transform(*sys.argv[1:])))
except Exception:
sys.exit(2)