forked from unimatrix/web
24 lines
951 B
Python
24 lines
951 B
Python
"""Validate uploaded raster files and make a bounded, metadata-free emblem."""
|
|
import io
|
|
import sys
|
|
import warnings
|
|
from PIL import Image
|
|
|
|
Image.MAX_IMAGE_PIXELS = 4194304
|
|
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
|
data = sys.stdin.buffer.read(2097153)
|
|
if not data or len(data)>2097152:
|
|
raise ValueError('Image exceeds 2 MB')
|
|
image = Image.open(io.BytesIO(data))
|
|
if image.format not in ('PNG','JPEG','WEBP') or getattr(image,'n_frames',1)!=1:
|
|
raise ValueError('Use a still PNG, JPEG or WebP image')
|
|
if min(image.size)<32 or max(image.size)>4096:
|
|
raise ValueError('Invalid emblem dimensions')
|
|
image.verify()
|
|
image = Image.open(io.BytesIO(data)).convert('RGBA')
|
|
png = len(sys.argv) == 2 and sys.argv[1] == 'png'
|
|
image.thumbnail((128,128) if png else (512,512), Image.Resampling.LANCZOS)
|
|
if png:
|
|
image.save(sys.stdout.buffer, 'PNG', optimize=True)
|
|
else:
|
|
image.save(sys.stdout.buffer, 'WEBP', quality=90, method=6)
|

Staff