fix: preserve PNG transparency at original sample depth

This commit is contained in:
Artyom
2026-11-06 23:51:58 +03:00
parent 6e97bdbe96
commit 42575281b3
35 changed files with 1234 additions and 1 deletions
@@ -8,7 +8,8 @@ from concurrent.futures.process import BrokenProcessPool
from dataclasses import dataclass
from io import BytesIO
from PIL import Image, ImageOps
from PIL import Image, ImageChops, ImageOps
from PIL.PngImagePlugin import PngImageFile
from messenger.attachments.application.ports import Rendition
from messenger.attachments.domain.errors import (
@@ -39,6 +40,7 @@ JPEG = {1: {"quality": 85, "optimize": True}, 2: {"quality": 90, "optimize": Tru
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
@dataclass(frozen=True, slots=True)
@@ -86,6 +88,32 @@ class PillowImageInspector:
return ImageInfo(kind, width, height)
def rgb_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(
mask, image.getchannel(channel).point([255 if i == value else 0 for i in range(256)])
)
return mask
def apply_png_transparency(image: PngImageFile, data: bytes) -> None:
if (transparent := image.info.get("transparency")) is None:
return
depth = read_png_header(data)[2]
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:
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)
image.info.pop("transparency")
def flatten(image: Image.Image) -> Image.Image:
if image.mode in WIDE_MODES:
image = image.convert("I")
@@ -122,6 +150,8 @@ def decoded(data: bytes, max_pixels: int) -> tuple[Image.Image, int, int]:
width, height = image.size
if width * height > max_pixels:
raise UnreadableImage("изображение больше допустимого числа пикселей")
if isinstance(image, PngImageFile):
apply_png_transparency(image, data)
image.draft(None, fit(width, height, OPTIMIZED_BOX))
stored = image.size
ImageOps.exif_transpose(image, in_place=True)