99 lines
3.2 KiB
Python
99 lines
3.2 KiB
Python
from __future__ import annotations
|
|
|
|
import hashlib
|
|
from dataclasses import dataclass
|
|
from io import BytesIO
|
|
|
|
from PIL import Image, ImageOps, UnidentifiedImageError
|
|
|
|
|
|
class PermanentImageError(Exception):
|
|
def __init__(self, code: str) -> None:
|
|
super().__init__(code)
|
|
self.code = code
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class GeneratedVariant:
|
|
name: str
|
|
content_type: str
|
|
width: int
|
|
height: int
|
|
sha256: str
|
|
content: bytes
|
|
|
|
|
|
def _jpeg_image(image: Image.Image) -> Image.Image:
|
|
if image.mode in {'RGBA', 'LA'} or 'transparency' in image.info:
|
|
rgba = image.convert('RGBA')
|
|
background = Image.new('RGBA', rgba.size, 'white')
|
|
background.alpha_composite(rgba)
|
|
return background.convert('RGB')
|
|
return image.convert('RGB')
|
|
|
|
|
|
def _encode(image: Image.Image, fmt: str, **options) -> bytes:
|
|
output = BytesIO()
|
|
image.save(output, format=fmt, **options)
|
|
return output.getvalue()
|
|
|
|
|
|
def _variant(name: str, content_type: str, image: Image.Image, content: bytes) -> GeneratedVariant:
|
|
return GeneratedVariant(
|
|
name=name,
|
|
content_type=content_type,
|
|
width=image.width,
|
|
height=image.height,
|
|
sha256=hashlib.sha256(content).hexdigest(),
|
|
content=content,
|
|
)
|
|
|
|
|
|
def process_image(
|
|
source: bytes,
|
|
declared_type: str,
|
|
expected_sha256: str,
|
|
max_pixels: int,
|
|
thumbnail_quality: int,
|
|
crop_quality: int,
|
|
webp_quality: int,
|
|
) -> tuple[GeneratedVariant, ...]:
|
|
if hashlib.sha256(source).hexdigest() != expected_sha256:
|
|
raise PermanentImageError('checksum_mismatch')
|
|
try:
|
|
with Image.open(BytesIO(source)) as opened:
|
|
actual = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}.get(opened.format or '')
|
|
if actual != declared_type:
|
|
raise PermanentImageError('unsupported_media_type')
|
|
if opened.width * opened.height > max_pixels:
|
|
raise PermanentImageError('image_too_large')
|
|
opened.load()
|
|
oriented = ImageOps.exif_transpose(opened)
|
|
base = oriented.copy()
|
|
except PermanentImageError:
|
|
raise
|
|
except (Image.DecompressionBombError, UnidentifiedImageError, OSError, SyntaxError) as error:
|
|
raise PermanentImageError('invalid_image') from error
|
|
|
|
thumbnail = _jpeg_image(base.copy())
|
|
thumbnail.thumbnail((256, 256), Image.Resampling.LANCZOS, reducing_gap=3.0)
|
|
thumbnail_bytes = _encode(
|
|
thumbnail, 'JPEG', quality=thumbnail_quality, optimize=True, progressive=True
|
|
)
|
|
|
|
crop_source = _jpeg_image(base.copy())
|
|
crop = ImageOps.fit(
|
|
crop_source, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)
|
|
)
|
|
crop_bytes = _encode(crop, 'JPEG', quality=crop_quality, optimize=True, progressive=True)
|
|
|
|
optimized = base.copy()
|
|
optimized.thumbnail((1280, 1280), Image.Resampling.LANCZOS, reducing_gap=3.0)
|
|
optimized_bytes = _encode(optimized, 'WEBP', quality=webp_quality, method=6)
|
|
|
|
return (
|
|
_variant('thumbnail', 'image/jpeg', thumbnail, thumbnail_bytes),
|
|
_variant('crop', 'image/jpeg', crop, crop_bytes),
|
|
_variant('optimized', 'image/webp', optimized, optimized_bytes),
|
|
)
|