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
14 changes: 14 additions & 0 deletions Tests/test_imagepalette.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,20 @@ def test_sanity() -> None:
assert len(palette.colors) == 256


def test_colors_rawmode() -> None:
palette = ImagePalette.raw(
"BGRX",
bytes.fromhex("00000000ffffff000000ff0000ff0000ff000000"),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
bytes.fromhex("00000000ffffff000000ff0000ff0000ff000000"),
"BGRX", (0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 0)

This makes it much easier to read, swap around the channels in your head, and understand how the BGRX values are transformed into the expected RGB values.

)
assert palette.colors == {
(0, 0, 0): 0,
(255, 255, 255): 1,
(255, 0, 0): 2,
(0, 255, 0): 3,
(0, 0, 255): 4,
}


def test_reload() -> None:
with Image.open("Tests/images/hopper.gif") as im:
original = im.copy()
Expand Down
12 changes: 10 additions & 2 deletions src/PIL/ImagePalette.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,18 @@ def palette(self, palette: Sequence[int] | bytes | bytearray) -> None:
@property
def colors(self) -> dict[tuple[int, ...], int]:
if self._colors is None:
palette = self.palette
if self.rawmode:
from . import Image

im = Image.core.new("P", (0, 0))
im.putpalette(self.mode, self.rawmode, palette)
palette = im.getpalette(self.mode, self.mode)

mode_len = len(self.mode)
self._colors = {}
for i in range(0, len(self.palette), mode_len):
color = tuple(self.palette[i : i + mode_len])
for i in range(0, len(palette), mode_len):
color = tuple(palette[i : i + mode_len])
if color in self._colors:
continue
self._colors[color] = i // mode_len
Expand Down
Loading