106 lines
3.9 KiB
Python
106 lines
3.9 KiB
Python
"""Thumbnail, crop и WebP; один ограниченный процесс, последовательная обработка."""
|
||
|
||
import hashlib
|
||
from pathlib import Path
|
||
|
||
from PIL import Image, ImageOps
|
||
|
||
from app.core.image_processing import ImageSettings
|
||
from app.domain.image_validation import decode_image
|
||
from app.schemas.attachment import PipelineResult, Variant
|
||
|
||
|
||
def fitted_size(size: tuple[int, int], maximum: int) -> tuple[int, int]:
|
||
"""Вписать без увеличения, округляя вниз, минимум один пиксель."""
|
||
longest = max(size)
|
||
result = size
|
||
if longest > maximum:
|
||
result = (
|
||
max(1, size[0] * maximum // longest),
|
||
max(1, size[1] * maximum // longest),
|
||
)
|
||
return result
|
||
|
||
|
||
def describe_variant(
|
||
name: str, content_type: str, path: Path, size: tuple[int, int]
|
||
) -> Variant:
|
||
checksum = hashlib.sha256()
|
||
with path.open("rb") as source:
|
||
for chunk in iter(lambda: source.read(65536), b""):
|
||
checksum.update(chunk)
|
||
return Variant(
|
||
name=name,
|
||
content_type=content_type,
|
||
size_bytes=path.stat().st_size,
|
||
width=size[0],
|
||
height=size[1],
|
||
sha256=checksum.hexdigest(),
|
||
)
|
||
|
||
|
||
def save_jpeg(image: Image.Image, destination: Path, quality: int) -> None:
|
||
"""Белая подложка и новый image без EXIF/ICC/XMP/текстовых метаданных."""
|
||
with Image.new("RGB", image.size, "white") as clean:
|
||
with image.getchannel("A") as alpha:
|
||
clean.paste(image, mask=alpha)
|
||
clean.save(destination, format="JPEG", quality=quality, exif=b"")
|
||
|
||
|
||
def create_thumbnail(image: Image.Image, destination: Path, quality: int) -> Variant:
|
||
size = fitted_size(image.size, 256)
|
||
with image.resize(size, Image.Resampling.LANCZOS) as resized:
|
||
save_jpeg(resized, destination, quality)
|
||
return describe_variant("thumbnail", "image/jpeg", destination, size)
|
||
|
||
|
||
def create_crop(image: Image.Image, destination: Path, quality: int) -> Variant:
|
||
"""Центрированный JPEG 128×128; маленький исходник допускает увеличение."""
|
||
with ImageOps.fit(
|
||
image, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)
|
||
) as crop:
|
||
save_jpeg(crop, destination, quality)
|
||
return describe_variant("crop", "image/jpeg", destination, (128, 128))
|
||
|
||
|
||
def create_optimized(
|
||
image: Image.Image, destination: Path, settings: ImageSettings
|
||
) -> Variant:
|
||
"""WebP ≤1280×1280 без увеличения; alpha сохраняется, метаданные удаляются."""
|
||
size = fitted_size(image.size, 1280)
|
||
with image.resize(size, Image.Resampling.LANCZOS) as resized:
|
||
with Image.new("RGBA", size) as clean:
|
||
clean.paste(resized)
|
||
clean.save(
|
||
destination,
|
||
format="WEBP",
|
||
lossless=False,
|
||
quality=settings.webp_quality,
|
||
method=settings.webp_method,
|
||
exif=b"",
|
||
icc_profile=b"",
|
||
xmp=b"",
|
||
)
|
||
return describe_variant("optimized", "image/webp", destination, size)
|
||
|
||
|
||
def create_variants(
|
||
source: Path,
|
||
directory: Path,
|
||
content_type: str,
|
||
max_pixels: int,
|
||
settings: ImageSettings,
|
||
) -> PipelineResult:
|
||
decode_image(source, content_type, max_pixels)
|
||
with Image.open(source, formats=["PNG", "JPEG"]) as image:
|
||
ImageOps.exif_transpose(image, in_place=True)
|
||
with image.convert("RGBA") as pixels:
|
||
variants = [
|
||
create_thumbnail(
|
||
pixels, directory / "thumbnail.jpg", settings.jpeg_quality
|
||
),
|
||
create_crop(pixels, directory / "crop.jpg", settings.jpeg_quality),
|
||
create_optimized(pixels, directory / "optimized.webp", settings),
|
||
]
|
||
return PipelineResult(variants=variants)
|