Preserve infrastructure redeliveries and flatten PNG transparency

This commit is contained in:
Artyom
2026-11-06 23:33:51 +03:00
parent ef55f9ac0a
commit 3fad49d6b9
19 changed files with 592 additions and 17 deletions
+39 -3
View File
@@ -5,7 +5,12 @@ from PIL import Image
from messenger.attachments.application.ports import Rendition
from messenger.attachments.domain.errors import ImageTooDemanding, UnreadableImage
from messenger.attachments.infrastructure.images import RenderLimits, render_variants
from messenger.attachments.domain.values import ImageKind
from messenger.attachments.infrastructure.images import (
PillowImageInspector,
RenderLimits,
render_variants,
)
from pictures import SAMPLE
LIMITS = RenderLimits(max_bytes=10_485_760, max_pixels=40_000_000)
@@ -22,8 +27,8 @@ def encoded(image: Image.Image, kind: str = "PNG", **options: object) -> bytes:
return buffer.getvalue()
def rendered(data: bytes) -> dict[str, Image.Image]:
renditions: list[Rendition] = render_variants(data, LIMITS)
def rendered(data: bytes, version: int = 1) -> dict[str, Image.Image]:
renditions: list[Rendition] = render_variants(data, LIMITS, version)
assert [rendition.name for rendition in renditions] == ["thumbnail", "crop", "optimized"]
images = {}
for rendition in renditions:
@@ -87,6 +92,37 @@ def test_palette_transparency_is_composed_on_white() -> None:
assert image.convert("RGB").getpixel((5, 5)) == (255, 255, 255)
@pytest.mark.parametrize("version", [1, 2])
@pytest.mark.parametrize(
("mode", "transparent", "opaque", "expected"),
[
("RGB", (255, 0, 0), (32, 96, 160), (32, 96, 160)),
("L", 0, 96, (96, 96, 96)),
("1", 0, 255, (255, 255, 255)),
("1", 255, 0, (0, 0, 0)),
("I;16", 12345, 12346, (48, 48, 48)),
],
)
async def test_png_trns_is_white_without_changing_opaque_pixels(
version: int,
mode: str,
transparent: int | tuple[int, int, int],
opaque: int | tuple[int, int, int],
expected: tuple[int, int, int],
) -> None:
source = Image.new(mode, (64, 64), transparent)
source.paste(Image.new(mode, (32, 64), opaque), (32, 0))
assert source.getpixel((58, 32)) == opaque
data = encoded(source, transparency=transparent)
info = await PillowImageInspector(LIMITS.max_pixels, 1).inspect(data, ImageKind.PNG)
assert (info.width, info.height) == (64, 64)
for image in rendered(data, version).values():
assert image.getpixel((5, image.height // 2)) == (255, 255, 255)
pixel = image.getpixel((image.width - 6, image.height // 2))
assert isinstance(pixel, tuple)
assert all(abs(a - b) <= 3 for a, b in zip(pixel, expected, strict=True))
@pytest.mark.parametrize(
("orientation", "thumbnail", "optimized"),
[(6, (128, 256), (200, 400)), (3, (256, 128), (400, 200))],