Added rawmode argument to getpalette()

This commit is contained in:
Andrew Murray 2022-02-17 10:04:43 +11:00
parent bd4e20f8c2
commit 852859476b
3 changed files with 32 additions and 2 deletions

View File

@ -1,3 +1,5 @@
from PIL import Image
from .helper import hopper
@ -17,3 +19,28 @@ def test_palette():
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))
rgb = im.getpalette("RGB")
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]
rgba = im.getpalette("RGBA")
assert len(rgba) == 256 * 4
assert rgba[:4] == [1, 2, 3, 4]

View File

@ -1401,19 +1401,21 @@ class Image:
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.
: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
return list(self.im.getpalette(mode, rawmode))
def getpixel(self, xy):
"""

View File

@ -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},