From ef8fd7f8b97159cb767e1bd640e7240dcf083984 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 9 May 2022 18:50:54 +1000 Subject: [PATCH] Populate Python palette in fromarray() --- Tests/test_image_array.py | 12 ++++++++++++ src/PIL/Image.py | 4 ++++ 2 files changed, 16 insertions(+) diff --git a/Tests/test_image_array.py b/Tests/test_image_array.py index 5c9cdd7e0..7168c4265 100644 --- a/Tests/test_image_array.py +++ b/Tests/test_image_array.py @@ -80,3 +80,15 @@ def test_fromarray(): with pytest.raises(TypeError): wrapped = Wrapper(test("L"), {"shape": (100, 128)}) Image.fromarray(wrapped) + + +def test_fromarray_palette(): + # Arrange + i = im.convert("L") + a = numpy.array(i) + + # Act + out = Image.fromarray(a, "P") + + # Assert that the Python and C palettes match + assert len(out.palette.colors) == len(out.im.getpalette()) / 3 diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 99c7ba0d1..c141da09f 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -2838,6 +2838,10 @@ def frombuffer(mode, size, data, decoder_name="raw", *args): if args[0] in _MAPMODES: im = new(mode, (1, 1)) im = im._new(core.map_buffer(data, size, decoder_name, 0, args)) + if mode == "P": + from . import ImagePalette + + im.palette = ImagePalette.ImagePalette("RGB", im.im.getpalette("RGB")) im.readonly = 1 return im