Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Tests/test_imageops.py
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,31 @@ def test_palette_operation_keeps_alpha() -> None:
assert palette == [255, 255, 255, 0, 0, 255, 255, 128]


@pytest.mark.parametrize(
"mode, transparent, opaque",
(
("1", 0, 255),
("1", 255, 0),
("L", 31, 224),
("RGB", (1, 12, 32), (254, 243, 223)),
),
)
def test_invert_keeps_transparent_pixels(
mode: str, transparent: int | tuple[int, ...], opaque: int | tuple[int, ...]
) -> None:
im = Image.new(mode, (2, 1), transparent)
im.putpixel((1, 0), opaque)
im.info["transparency"] = transparent

result = ImageOps.invert(im)

assert result.mode == mode
assert result.getpixel((0, 0)) == opaque
assert result.info["transparency"] == opaque
assert im.info["transparency"] == transparent
assert result.convert("RGBA").getchannel("A").tobytes() == b"\x00\xff"


def test_palette_histogram_operation_not_supported() -> None:
im = hopper("P")
with pytest.raises(NotImplementedError, match="mode P support coming soon"):
Expand Down
6 changes: 6 additions & 0 deletions docs/releasenotes/13.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,12 @@ Two new image processing operations are available in ImageOps.
Other changes
=============

Preserve transparency when inverting images
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

:py:func:`~PIL.ImageOps.invert` now updates the transparent color in ``1``, ``L``
and ``RGB`` images so that the same pixels remain transparent after inversion.

PCX and ZIP decoder row sizes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Expand Down
12 changes: 11 additions & 1 deletion src/PIL/ImageOps.py
Original file line number Diff line number Diff line change
Expand Up @@ -786,7 +786,17 @@ def invert(image: Image.Image) -> Image.Image:
:return: An image.
"""
lut = list(range(255, -1, -1))
return image.point(lut) if image.mode == "1" else _lut(image, lut, palette=True)
result = image.point(lut) if image.mode == "1" else _lut(image, lut, palette=True)

transparency = result.info.get("transparency")
# Match the 8-bit samples used when converting the color key to alpha.
if image.mode in ("1", "L") and isinstance(transparency, int):
result.info["transparency"] = lut[transparency & 255]
elif image.mode == "RGB" and isinstance(transparency, (tuple, list)):
result.info["transparency"] = tuple(
lut[channel & 255] for channel in transparency
)
return result


def mirror(image: Image.Image) -> Image.Image:
Expand Down