forked from mtusi2026/mtusi2026lab6
feat: перенос структуры приложения из пятой лабы
This commit is contained in:
+132
@@ -0,0 +1,132 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import math
|
||||
from typing import TypedDict
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
MAX_IMAGE_PIXELS = 40_000_000
|
||||
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
|
||||
|
||||
|
||||
class GeneratedVariant(TypedDict):
|
||||
name: str
|
||||
content_type: str
|
||||
data: bytes
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
|
||||
|
||||
def _calculate_contained_dimensions(orig_w: int, orig_h: int, max_w: int, max_h: int) -> tuple[int, int]:
|
||||
"""Вычисляет размеры, вписанные в max_w x max_h с сохранением пропорций,
|
||||
без увеличения маленьких исходников, с округлением вниз (floor) и минимумом 1px."""
|
||||
if orig_w <= max_w and orig_h <= max_h:
|
||||
return orig_w, orig_h
|
||||
scale = min(max_w / orig_w, max_h / orig_h)
|
||||
new_w = max(1, math.floor(orig_w * scale))
|
||||
new_h = max(1, math.floor(orig_h * scale))
|
||||
return new_w, new_h
|
||||
|
||||
|
||||
def _flatten_to_rgb(img: Image.Image) -> Image.Image:
|
||||
"""Накладывает альфа-канал на белый фон для форматов без поддержки прозрачности (JPEG)."""
|
||||
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
|
||||
rgba = img.convert("RGBA")
|
||||
background = Image.new("RGB", rgba.size, (255, 255, 255))
|
||||
background.paste(rgba, mask=rgba.split()[3])
|
||||
return background
|
||||
if img.mode != "RGB":
|
||||
return img.convert("RGB")
|
||||
return img
|
||||
|
||||
|
||||
def generate_thumbnail(img: Image.Image) -> tuple[bytes, int, int]:
|
||||
"""Генерирует thumbnail: вписан в 256x256 без апскейла, JPEG, alpha на белый фон.
|
||||
|
||||
Размеры рассчитываются строго с округлением вниз (floor) и минимумом 1px.
|
||||
Возвращает (jpeg_bytes, width, height).
|
||||
"""
|
||||
target_w, target_h = _calculate_contained_dimensions(img.width, img.height, 256, 256)
|
||||
if (img.width, img.height) != (target_w, target_h):
|
||||
thumb = img.resize((target_w, target_h), Image.Resampling.LANCZOS)
|
||||
else:
|
||||
thumb = img.copy()
|
||||
rgb = _flatten_to_rgb(thumb)
|
||||
|
||||
buf = io.BytesIO()
|
||||
rgb.save(buf, format="JPEG", quality=85, optimize=True)
|
||||
data = buf.getvalue()
|
||||
return data, rgb.width, rgb.height
|
||||
|
||||
|
||||
def generate_crop(img: Image.Image) -> tuple[bytes, int, int]:
|
||||
"""Генерирует crop: центрированный квадрат 128x128 (с апскейлом для меньших), JPEG.
|
||||
|
||||
Возвращает (jpeg_bytes, width, height).
|
||||
"""
|
||||
cropped = ImageOps.fit(img, (128, 128), method=Image.Resampling.LANCZOS)
|
||||
rgb = _flatten_to_rgb(cropped)
|
||||
|
||||
buf = io.BytesIO()
|
||||
rgb.save(buf, format="JPEG", quality=85, optimize=True)
|
||||
data = buf.getvalue()
|
||||
return data, rgb.width, rgb.height
|
||||
|
||||
|
||||
def generate_optimized(img: Image.Image) -> tuple[bytes, int, int]:
|
||||
"""Генерирует optimized: WebP, вписан в 1280x1280 без апскейла, удаление EXIF.
|
||||
|
||||
Размеры рассчитываются строго с округлением вниз (floor) и минимумом 1px.
|
||||
Возвращает (webp_bytes, width, height).
|
||||
"""
|
||||
target_w, target_h = _calculate_contained_dimensions(img.width, img.height, 1280, 1280)
|
||||
if (img.width, img.height) != (target_w, target_h):
|
||||
opt = img.resize((target_w, target_h), Image.Resampling.LANCZOS)
|
||||
else:
|
||||
opt = img.copy()
|
||||
|
||||
if opt.mode not in ("RGB", "RGBA"):
|
||||
opt = opt.convert("RGBA" if "transparency" in opt.info else "RGB")
|
||||
|
||||
buf = io.BytesIO()
|
||||
opt.save(buf, format="WEBP", quality=80, method=4)
|
||||
data = buf.getvalue()
|
||||
return data, opt.width, opt.height
|
||||
|
||||
|
||||
def process_image_variants(raw_bytes: bytes) -> list[GeneratedVariant]:
|
||||
"""Безопасно декодирует сырые байты оригинала и генерирует thumbnail, crop, optimized.
|
||||
|
||||
Применяет EXIF orientation к базовому изображению.
|
||||
"""
|
||||
with Image.open(io.BytesIO(raw_bytes)) as img:
|
||||
w, h = img.size
|
||||
if w * h > MAX_IMAGE_PIXELS:
|
||||
raise ValueError("decompression bomb: image exceeds pixel limit")
|
||||
img.load()
|
||||
transposed = ImageOps.exif_transpose(img) or img
|
||||
|
||||
thumb_bytes, thumb_w, thumb_h = generate_thumbnail(transposed)
|
||||
crop_bytes, crop_w, crop_h = generate_crop(transposed)
|
||||
opt_bytes, opt_w, opt_h = generate_optimized(transposed)
|
||||
|
||||
def make_entry(name: str, ctype: str, data: bytes, w: int, h: int) -> GeneratedVariant:
|
||||
return {
|
||||
"name": name,
|
||||
"content_type": ctype,
|
||||
"data": data,
|
||||
"size_bytes": len(data),
|
||||
"width": w,
|
||||
"height": h,
|
||||
"sha256": hashlib.sha256(data).hexdigest(),
|
||||
}
|
||||
|
||||
return [
|
||||
make_entry("thumbnail", "image/jpeg", thumb_bytes, thumb_w, thumb_h),
|
||||
make_entry("crop", "image/jpeg", crop_bytes, crop_w, crop_h),
|
||||
make_entry("optimized", "image/webp", opt_bytes, opt_w, opt_h),
|
||||
]
|
||||
Reference in New Issue
Block a user