61 lines
2.4 KiB
Python
61 lines
2.4 KiB
Python
"""Bounded subprocess: trusted local paths, no URLs, no credentials."""
|
|
import hashlib
|
|
import json
|
|
import resource
|
|
import sys
|
|
import warnings
|
|
from pathlib import Path
|
|
from PIL import Image, ImageOps, UnidentifiedImageError
|
|
|
|
# Bound decoder subprocess independently of container and Go memory.
|
|
resource.setrlimit(resource.RLIMIT_AS, (1024 * 1024 * 1024, 1024 * 1024 * 1024))
|
|
Image.MAX_IMAGE_PIXELS = 40_000_000
|
|
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
|
|
|
|
|
def contain(image, bound):
|
|
w, h = image.size
|
|
if max(w, h) <= bound:
|
|
return image.copy()
|
|
if w >= h:
|
|
size = (bound, max(1, h * bound // w))
|
|
else:
|
|
size = (max(1, w * bound // h), bound)
|
|
return image.resize(size, Image.Resampling.LANCZOS)
|
|
|
|
|
|
def main():
|
|
source, target = map(Path, sys.argv[1:3])
|
|
if source.stat().st_size > 10_485_760:
|
|
raise ValueError('size')
|
|
with Image.open(source) as original:
|
|
if original.format not in ('PNG', 'JPEG') or original.width * original.height > 40_000_000:
|
|
raise ValueError('format or pixels')
|
|
original.load()
|
|
oriented = ImageOps.exif_transpose(original)
|
|
rgba = oriented.convert('RGBA')
|
|
image = Image.new('RGB', rgba.size, 'white')
|
|
image.paste(rgba, mask=rgba.getchannel('A'))
|
|
# New pixel images + empty info ensure EXIF/ICC/text are never propagated.
|
|
variants = []
|
|
for name, result, kind, quality in (
|
|
('thumbnail', contain(image, 256), 'JPEG', 85),
|
|
('crop', ImageOps.fit(image, (128, 128), method=Image.Resampling.LANCZOS, centering=(.5, .5)), 'JPEG', 85),
|
|
('optimized', contain(image, 1280), 'WEBP', 80),
|
|
):
|
|
result.info.clear()
|
|
path = target / name
|
|
result.save(path, format=kind, quality=quality, **({'method': 4} if kind == 'WEBP' else {}))
|
|
data = path.read_bytes()
|
|
variants.append(dict(name=name, content_type='image/webp' if kind == 'WEBP' else 'image/jpeg',
|
|
size_bytes=len(data), width=result.width, height=result.height,
|
|
sha256=hashlib.sha256(data).hexdigest()))
|
|
print(json.dumps(variants))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError, Image.DecompressionBombWarning):
|
|
sys.exit(2) # permanent invalid_image; details never reach public API
|