Bound PNG transparency buffers within worker memory limits

This commit is contained in:
Artyom
2026-11-07 00:47:22 +03:00
parent 429f12d0bc
commit 1a80205249
18 changed files with 928 additions and 11 deletions
@@ -5,6 +5,7 @@ import warnings
from collections.abc import Callable
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures.process import BrokenProcessPool
from contextlib import closing
from dataclasses import dataclass
from io import BytesIO
@@ -41,6 +42,7 @@ WEBP = {1: {"quality": 80, "method": 4}, 2: {"quality": 85, "method": 4}}
ENCODINGS = {"JPEG": (ImageKind.JPEG.value, "jpg"), "WEBP": ("image/webp", "webp")}
REDUCING_GAP = 3.0
PNG_WIDE_DEPTH = 16
COLOR_TILE_SIDE = 256
@dataclass(frozen=True, slots=True)
@@ -88,7 +90,28 @@ class PillowImageInspector:
return ImageInfo(kind, width, height)
def map_tiles(
image: Image.Image, mode: str, transform: Callable[[Image.Image], Image.Image]
) -> Image.Image:
result = Image.new(mode, image.size)
for y in range(0, image.height, COLOR_TILE_SIDE):
for x in range(0, image.width, COLOR_TILE_SIDE):
box = (
x,
y,
min(x + COLOR_TILE_SIDE, image.width),
min(y + COLOR_TILE_SIDE, image.height),
)
with closing(image.crop(box)) as tile, closing(transform(tile)) as transformed:
result.paste(transformed, box)
return result
def rgb_mask(image: Image.Image, color: tuple[int, ...]) -> Image.Image:
return map_tiles(image, "L", lambda tile: rgb_tile_mask(tile, color))
def rgb_tile_mask(image: Image.Image, color: tuple[int, ...]) -> Image.Image:
mask = Image.new("L", image.size, 255)
for channel, value in zip("RGB", color, strict=True):
mask = ImageChops.multiply(
@@ -104,17 +127,25 @@ def apply_png_transparency(image: PngImageFile, data: bytes) -> None:
if image.mode == "L" and depth in (2, 4):
image.info["transparency"] = transparent * 255 // ((1 << depth) - 1)
elif image.mode == "RGB" and depth == PNG_WIDE_DEPTH:
with PngImageFile(BytesIO(data)) as low:
with closing(PngImageFile(BytesIO(data))) as low:
low.tile = [tile._replace(args="RGB;16L") for tile in low.tile]
mask = rgb_mask(low, tuple(value & 255 for value in transparent))
mask = ImageChops.multiply(
mask, rgb_mask(image, tuple(value >> 8 for value in transparent))
)
image.paste((255, 255, 255), mask=mask)
with (
closing(mask),
closing(rgb_mask(image, tuple(value >> 8 for value in transparent))) as high,
closing(ImageChops.multiply(mask, high)) as combined,
):
image.paste((255, 255, 255), mask=combined)
image.info.pop("transparency")
def flatten(image: Image.Image) -> Image.Image:
if image.mode == "RGB" and "transparency" not in image.info:
return image
return map_tiles(image, "RGB", flatten_tile)
def flatten_tile(image: Image.Image) -> Image.Image:
if image.mode in WIDE_MODES:
image = image.convert("I")
if (transparent := image.info.pop("transparency", None)) is not None:
@@ -157,7 +188,10 @@ def decoded(data: bytes, max_pixels: int) -> tuple[Image.Image, int, int]:
ImageOps.exif_transpose(image, in_place=True)
if image.size != stored:
width, height = height, width
return flatten(image), width, height
upright = flatten(image)
if upright is not image:
image.close()
return upright, width, height
except UnreadableImage, MemoryError:
raise
except Exception as error: