forked from mtusi2026/mtusi2026lab5
level 3
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
"""JPEG thumbnail for pipeline v1. Crop and WebP belong to the next grade."""
|
||||
import io
|
||||
from typing import Tuple
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
from .images import MAX_IMAGE_PIXELS
|
||||
|
||||
THUMBNAIL_BOX = 256
|
||||
# Pillow's default 75 is fine for a preview; the contract only fixes the pixel size.
|
||||
_JPEG_QUALITY = 85
|
||||
|
||||
|
||||
class ImageRejected(Exception):
|
||||
"""The bytes are not a PNG/JPEG we can decode inside the pixel limit."""
|
||||
|
||||
|
||||
def _fit(width: int, height: int, box: int) -> Tuple[int, int]:
|
||||
"""Fit inside box×box, keep the aspect ratio, never upscale, round down, at least 1 px."""
|
||||
if width <= box and height <= box:
|
||||
return width, height
|
||||
fitted_width = box
|
||||
fitted_height = (height * box) // width
|
||||
if fitted_height > box:
|
||||
fitted_height = box
|
||||
fitted_width = (width * box) // height
|
||||
return max(1, fitted_width), max(1, fitted_height)
|
||||
|
||||
|
||||
def _on_white(image: Image.Image) -> Image.Image:
|
||||
if image.mode == 'RGB':
|
||||
return image
|
||||
rgba = image.convert('RGBA')
|
||||
background = Image.new('RGB', rgba.size, (255, 255, 255))
|
||||
background.paste(rgba, mask=rgba.getchannel('A'))
|
||||
return background
|
||||
|
||||
|
||||
def make_thumbnail(data: bytes) -> Tuple[bytes, int, int]:
|
||||
"""Return JPEG bytes and the size actually written. 320×200 becomes 256×160."""
|
||||
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
|
||||
source = Image.open(io.BytesIO(data))
|
||||
try:
|
||||
oriented = ImageOps.exif_transpose(source)
|
||||
if oriented is not source:
|
||||
source.close()
|
||||
source = oriented
|
||||
source.load()
|
||||
width, height = source.size
|
||||
if width <= 0 or height <= 0 or width * height > MAX_IMAGE_PIXELS:
|
||||
raise ImageRejected()
|
||||
fitted = _fit(width, height, THUMBNAIL_BOX)
|
||||
if fitted != (width, height):
|
||||
source = source.resize(fitted, Image.Resampling.LANCZOS)
|
||||
rgb = _on_white(source)
|
||||
buffer = io.BytesIO()
|
||||
rgb.save(buffer, format='JPEG', quality=_JPEG_QUALITY)
|
||||
return buffer.getvalue(), fitted[0], fitted[1]
|
||||
except ImageRejected:
|
||||
raise
|
||||
except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError):
|
||||
raise ImageRejected() from None
|
||||
finally:
|
||||
source.close()
|
||||
Reference in New Issue
Block a user