Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added rawmode argument to Image.getpalette() #6061

Merged
merged 6 commits into from Feb 20, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions Tests/test_image_getpalette.py
@@ -1,3 +1,5 @@
from PIL import Image

from .helper import hopper


Expand All @@ -17,3 +19,30 @@ def palette(mode):
assert palette("RGBA") is None
assert palette("CMYK") is None
assert palette("YCbCr") is None


def test_palette_rawmode():
im = Image.new("P", (1, 1))
im.putpalette((1, 2, 3))

for rawmode in ("RGB", None):
rgb = im.getpalette(rawmode)
assert len(rgb) == 256 * 3
assert rgb[:3] == [1, 2, 3]

# Convert the RGB palette to RGBA
rgba = im.getpalette("RGBA")
assert len(rgba) == 256 * 4
assert rgba[:4] == [1, 2, 3, 255]

im.putpalette((1, 2, 3, 4), "RGBA")

# Convert the RGBA palette to RGB
rgb = im.getpalette("RGB")
assert len(rgb) == 256 * 3
assert rgb[:3] == [1, 2, 3]

for rawmode in ("RGBA", None):
rgba = im.getpalette(rawmode)
assert len(rgba) == 256 * 4
assert rgba[:4] == [1, 2, 3, 4]
9 changes: 7 additions & 2 deletions src/PIL/Image.py
Expand Up @@ -1401,19 +1401,24 @@ def getim(self):
self.load()
return self.im.ptr

def getpalette(self):
def getpalette(self, rawmode="RGB"):
"""
Returns the image palette as a list.

:param rawmode: The mode in which to return the palette. ``None`` will
return the palette in its current mode.
hugovk marked this conversation as resolved.
Show resolved Hide resolved
:returns: A list of color values [r, g, b, ...], or None if the
image has no palette.
"""

self.load()
try:
return list(self.im.getpalette())
mode = self.im.getpalettemode()
except ValueError:
return None # no palette
if rawmode is None:
rawmode = mode
return list(self.im.getpalette(mode, rawmode))

def getpixel(self, xy):
"""
Expand Down
1 change: 1 addition & 0 deletions src/libImaging/Pack.c
Expand Up @@ -574,6 +574,7 @@ static struct {
/* true colour */
{"RGB", "RGB", 24, ImagingPackRGB},
{"RGB", "RGBX", 32, copy4},
{"RGB", "RGBA", 32, copy4},
{"RGB", "XRGB", 32, ImagingPackXRGB},
{"RGB", "BGR", 24, ImagingPackBGR},
{"RGB", "BGRX", 32, ImagingPackBGRX},
Expand Down