forked from mtusi2026/mtusi2026lab6
99 lines
3.2 KiB
Python
99 lines
3.2 KiB
Python
"""Обработка изображений: thumbnail 256×256, crop 128×128, optimized WebP."""
|
||
import hashlib
|
||
import io
|
||
import logging
|
||
|
||
from PIL import Image, ImageOps
|
||
|
||
from . import config
|
||
|
||
log = logging.getLogger("pipeline")
|
||
|
||
PIPELINE_VERSION = 1
|
||
Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS
|
||
|
||
THUMB_MAX = (256, 256)
|
||
CROP_SIDE = 128
|
||
OPT_MAX = (1280, 1280)
|
||
OPT_QUALITY = 82
|
||
JPEG_QUALITY = 85
|
||
|
||
|
||
def _open_normalized(data: bytes) -> Image.Image:
|
||
"""Открывает, применяет EXIF orientation, приводит к RGB с белым фоном для alpha."""
|
||
img = Image.open(io.BytesIO(data))
|
||
img = ImageOps.exif_transpose(img)
|
||
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
|
||
background = Image.new("RGB", img.size, (255, 255, 255))
|
||
img_rgba = img.convert("RGBA")
|
||
background.paste(img_rgba, mask=img_rgba.split()[-1])
|
||
img = background
|
||
elif img.mode != "RGB":
|
||
img = img.convert("RGB")
|
||
img.load()
|
||
return img
|
||
|
||
|
||
def _encode_jpeg(img: Image.Image) -> bytes:
|
||
buf = io.BytesIO()
|
||
img.save(buf, format="JPEG", quality=JPEG_QUALITY, optimize=True, progressive=True)
|
||
return buf.getvalue()
|
||
|
||
|
||
def _encode_webp(img: Image.Image) -> bytes:
|
||
buf = io.BytesIO()
|
||
img.save(buf, format="WEBP", quality=OPT_QUALITY, method=4)
|
||
return buf.getvalue()
|
||
|
||
|
||
def _make_thumbnail(img: Image.Image):
|
||
thumb = img.copy()
|
||
thumb.thumbnail(THUMB_MAX, Image.Resampling.LANCZOS)
|
||
if thumb.width < 1 or thumb.height < 1:
|
||
raise ValueError("thumbnail degenerate")
|
||
return _encode_jpeg(thumb), thumb.width, thumb.height
|
||
|
||
|
||
def _make_crop(img: Image.Image):
|
||
side = CROP_SIDE
|
||
# ImageOps.fit центрирует и ресайзит; для маленьких исходников увеличивает — разрешено.
|
||
crop = ImageOps.fit(img, (side, side), Image.Resampling.LANCZOS)
|
||
return _encode_jpeg(crop), side, side
|
||
|
||
|
||
def _make_optimized(img: Image.Image):
|
||
opt = img.copy()
|
||
opt.thumbnail(OPT_MAX, Image.Resampling.LANCZOS)
|
||
return _encode_webp(opt), opt.width, opt.height
|
||
|
||
|
||
def process(data: bytes):
|
||
"""Возвращает список вариантов: [{name, content_type, bytes, width, height, sha256, size_bytes}]."""
|
||
img = _open_normalized(data)
|
||
if img.width * img.height > config.MAX_IMAGE_PIXELS:
|
||
raise ValueError("too many pixels")
|
||
|
||
results = []
|
||
|
||
thumb_bytes, tw, th = _make_thumbnail(img)
|
||
results.append({
|
||
"name": "thumbnail", "content_type": "image/jpeg",
|
||
"bytes": thumb_bytes, "width": tw, "height": th,
|
||
"sha256": hashlib.sha256(thumb_bytes).hexdigest(), "size_bytes": len(thumb_bytes),
|
||
})
|
||
|
||
crop_bytes, cw, ch = _make_crop(img)
|
||
results.append({
|
||
"name": "crop", "content_type": "image/jpeg",
|
||
"bytes": crop_bytes, "width": cw, "height": ch,
|
||
"sha256": hashlib.sha256(crop_bytes).hexdigest(), "size_bytes": len(crop_bytes),
|
||
})
|
||
|
||
opt_bytes, ow, oh = _make_optimized(img)
|
||
results.append({
|
||
"name": "optimized", "content_type": "image/webp",
|
||
"bytes": opt_bytes, "width": ow, "height": oh,
|
||
"sha256": hashlib.sha256(opt_bytes).hexdigest(), "size_bytes": len(opt_bytes),
|
||
})
|
||
|
||
return results |