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
75 changes: 75 additions & 0 deletions Tests/test_image_quantize.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from PIL import Image

from .helper import (
assert_image_equal,
assert_image_similar,
has_feature_version,
hopper,
Expand Down Expand Up @@ -190,3 +191,77 @@ def test_empty_palette() -> None:

with pytest.raises(ValueError, match="empty palette"):
im.quantize(palette=p)


@pytest.mark.parametrize(
"mode, color, transparency",
(
("RGB", (255, 0, 0), (255, 0, 0)),
("L", 200, 200),
),
)
def test_transparency(
mode: str, color: int | tuple[int, ...], transparency: int | tuple[int, ...]
) -> None:
im = Image.new(mode, (2, 1))
im.putpixel((0, 0), color)
im.info["transparency"] = transparency

converted = im.quantize()
assert converted.info["transparency"] == converted.getpixel((0, 0))
assert converted.info["transparency"] != converted.getpixel((1, 0))


def test_transparency_p() -> None:
im = Image.new("P", (2, 1))
im.putpalette((0, 0, 0) * 5 + (255, 0, 0))
im.putpixel((0, 0), 5)
im.info["transparency"] = 5

converted = im.quantize()
assert converted.info["transparency"] == converted.getpixel((0, 0))
assert converted.info["transparency"] != converted.getpixel((1, 0))


def test_transparency_palette() -> None:
im = Image.new("RGB", (2, 1))
im.putpixel((0, 0), (255, 0, 0))
im.info["transparency"] = (255, 0, 0)

p = Image.new("P", (1, 1))
p.putpalette((0, 0, 0, 255, 0, 0))

converted = im.quantize(palette=p)
assert converted.info["transparency"] == 1

# If the transparent color is not in the palette
im.info["transparency"] = (0, 255, 0)
converted = im.quantize(palette=p)
assert "transparency" not in converted.info


@pytest.mark.parametrize(
"palette, transparency",
(
((255, 255, 255, 128, 128, 128, 0, 0, 0), b"\x00\x80\xff"),
((0, 0, 0, 0, 0, 255, 255, 0, 0, 0, 255, 0), b"\xff\x00\x80"),
),
)
def test_transparency_p_bytes(palette: tuple[int, ...], transparency: bytes) -> None:
im = Image.new("P", (len(palette) // 3, 1))
im.putpalette(palette)
im.putdata(range(im.width))
im.info["transparency"] = transparency

converted = im.quantize(im.width)
assert_image_equal(converted.convert("RGBA"), im.convert("RGBA"))


def test_transparency_p_bytes_opaque() -> None:
im = Image.new("P", (2, 1))
im.putpalette((0, 0, 0, 255, 0, 0))
im.putpixel((1, 0), 1)
im.info["transparency"] = b"\xff\xff"

converted = im.quantize()
assert "transparency" not in converted.info
43 changes: 43 additions & 0 deletions src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -1362,6 +1362,10 @@ def quantize(
new_im = self._new(im)
assert palette.palette is not None
new_im.palette = palette.palette.copy()
if self.mode != "L":
# L pixel values are used as the palette indexes,
# so the transparency is still correct
self._quantize_transparency(new_im)
return new_im

if kmeans < 0:
Expand All @@ -1375,9 +1379,48 @@ def quantize(
mode = im.im.getpalettemode()
palette_data = im.im.getpalette()[: colors * len(mode)]
im.palette = ImagePalette.ImagePalette(mode, palette_data)
self._quantize_transparency(im)

return im

def _quantize_transparency(self, im: Image) -> None:
# The transparency of this image does not apply to the new palette
t = im.info.pop("transparency", None)
if t is None:
return
assert im.palette is not None

if isinstance(t, bytes):
# Alpha values for each entry of the old palette.
# Give each color the same alpha in the new palette
if self.mode != "P":
return
palette = self.getpalette()
assert palette is not None
alpha = bytearray(b"\xff" * len(im.palette.colors))
for i in reversed(range(min(len(t), len(palette) // 3))):
index = im.palette.colors.get(tuple(palette[i * 3 : i * 3 + 3]))
if index is not None:
alpha[index] = t[i]
if alpha.count(255) != len(alpha):
im.info["transparency"] = bytes(alpha)
return

# Find the transparent color in the new palette
trns: tuple[int, ...]
if isinstance(t, tuple):
trns = t
elif self.mode == "P":
palette = self.getpalette()
assert palette is not None
trns = tuple(palette[t * 3 : t * 3 + 3])
else:
trns = (t, t, t)

index = im.palette.colors.get(trns)
if index is not None:
im.info["transparency"] = index

def copy(self) -> Image:
"""
Copies this image. Use this method if you wish to paste things
Expand Down