forked from mtusi2026/mtusi2026lab5
ЛР 5: асинхронная обработка изображений и идемпотентность pipeline
This commit is contained in:
+65
@@ -0,0 +1,65 @@
|
||||
"""Decode a bounded local input and write metadata-free variants for one job."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import warnings
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
|
||||
|
||||
def fit(image, edge):
|
||||
width, height = image.size
|
||||
longest = max(width, height)
|
||||
if longest <= edge:
|
||||
return image
|
||||
size = (max(1, width * edge // longest), max(1, height * edge // longest))
|
||||
return image.resize(size, Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
def white_rgb(image):
|
||||
if image.mode == "RGBA":
|
||||
background = Image.new("RGB", image.size, "white")
|
||||
background.paste(image, mask=image.getchannel("A"))
|
||||
return background
|
||||
return image.convert("RGB")
|
||||
|
||||
|
||||
def render(directory, mime, version):
|
||||
try:
|
||||
with Image.open(directory / "input", formats=("JPEG", "PNG")) as source:
|
||||
if Image.MIME[source.format] != mime or source.width * source.height > Image.MAX_IMAGE_PIXELS:
|
||||
return 2
|
||||
source.seek(0)
|
||||
# PNG may carry transparency in a tRNS chunk or in its alpha channel.
|
||||
mode = "RGBA" if "A" in source.getbands() or "transparency" in source.info else "RGB"
|
||||
ImageOps.exif_transpose(source, in_place=True)
|
||||
image = source.convert(mode)
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError,
|
||||
Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
return 2
|
||||
|
||||
square = min(image.size)
|
||||
left = (image.width - square) // 2
|
||||
top = (image.height - square) // 2
|
||||
outputs = [
|
||||
("thumbnail", fit(image, 256), "JPEG", 85),
|
||||
("crop", image.resize((128, 128), Image.Resampling.LANCZOS,
|
||||
box=(left, top, left + square, top + square)), "JPEG", 85),
|
||||
("optimized", fit(image, 1280), "WEBP", 80 if version == "1" else 90),
|
||||
]
|
||||
variants = []
|
||||
for name, pixels, format_name, quality in outputs:
|
||||
clean = white_rgb(pixels)
|
||||
clean.info.clear()
|
||||
clean.save(directory / name, format=format_name, quality=quality)
|
||||
variants.append({"width": clean.width, "height": clean.height})
|
||||
print(json.dumps(variants))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(render(Path(sys.argv[1]), sys.argv[2], sys.argv[3]))
|
||||
Reference in New Issue
Block a user