"""Варианты изображения. Оригинал не перекодируется.""" import io from PIL import Image, ImageOps, UnidentifiedImageError from PIL.Image import DecompressionBombError from blobs import MAX_PIXELS, header_size THUMB_BOX = 256 CROP_SIZE = 128 OPT_BOX = 1280 JPEG_QUALITY = 85 WEBP_QUALITY = 80 WEBP_METHOD = 4 Image.MAX_IMAGE_PIXELS = MAX_PIXELS class PermanentJobError(Exception): def __init__(self, code): super().__init__(code) self.code = code class TransientJobError(Exception): def __init__(self, code): super().__init__(code) self.code = code def _rgb(image): if image.mode == "RGBA" or image.mode == "LA" or (image.mode == "P" and "transparency" in image.info): rgba = image.convert("RGBA") background = Image.new("RGB", rgba.size, (255, 255, 255)) background.paste(rgba, mask=rgba.getchannel("A")) return background if image.mode == "RGB": return image return image.convert("RGB") def load_rgb(data, declared): size = header_size(data, declared) detected = None if data.startswith(b"\x89PNG\r\n\x1a\n"): detected = "image/png" elif data.startswith(b"\xff\xd8\xff"): detected = "image/jpeg" if size is None or detected != declared: raise PermanentJobError("invalid_image") width, height = size if width <= 0 or height <= 0 or width > MAX_PIXELS or height > MAX_PIXELS or width * height > MAX_PIXELS: raise PermanentJobError("invalid_image") try: with Image.open(io.BytesIO(data)) as image: image.load() oriented = ImageOps.exif_transpose(image) rgb = _rgb(oriented) rgb.load() return rgb except DecompressionBombError as exc: raise PermanentJobError("invalid_image") from exc except (UnidentifiedImageError, OSError, SyntaxError, ValueError) as exc: raise PermanentJobError("invalid_image") from exc def fit_inside(image, box): width, height = image.size if width <= box and height <= box: return image.copy() if width >= height: new_w = box new_h = max(1, (height * box) // width) else: new_h = box new_w = max(1, (width * box) // height) return image.resize((new_w, new_h), Image.Resampling.LANCZOS) def center_square(image, size): width, height = image.size side = min(width, height) left = (width - side) // 2 top = (height - side) // 2 cropped = image.crop((left, top, left + side, top + side)) if cropped.size != (size, size): cropped = cropped.resize((size, size), Image.Resampling.LANCZOS) return cropped def _jpeg(image): buffer = io.BytesIO() image.save(buffer, format="JPEG", quality=JPEG_QUALITY, optimize=True) return { "bytes": buffer.getvalue(), "content_type": "image/jpeg", "width": image.size[0], "height": image.size[1], } def _webp(image): buffer = io.BytesIO() image.save(buffer, format="WEBP", quality=WEBP_QUALITY, method=WEBP_METHOD) return { "bytes": buffer.getvalue(), "content_type": "image/webp", "width": image.size[0], "height": image.size[1], } def render(data, declared): rgb = load_rgb(data, declared) size = header_size(data, declared) thumb = fit_inside(rgb, THUMB_BOX) crop = center_square(rgb, CROP_SIZE) optimized = fit_inside(rgb, OPT_BOX) return { "original": { "bytes": data, "content_type": declared, "width": size[0], "height": size[1], }, "thumbnail": _jpeg(thumb), "crop": _jpeg(crop), "optimized": _webp(optimized), }