From 6790c2e37542addc3a60f0b116650f8de8ce3698 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 15 Mar 2019 17:30:28 +1100 Subject: [PATCH] Allow RGB and RGBA values for new P images --- Tests/test_image.py | 10 ++++++++++ src/PIL/Image.py | 9 ++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/Tests/test_image.py b/Tests/test_image.py index 330048057..07d57909f 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -522,6 +522,16 @@ class TestImage(PillowTestCase): _make_new(im, blank_p, ImagePalette.ImagePalette()) _make_new(im, blank_pa, ImagePalette.ImagePalette()) + def test_p_from_rgb_rgba(self): + for mode, color in [ + ("RGB", '#DDEEFF'), + ("RGB", (221, 238, 255)), + ("RGBA", (221, 238, 255, 255)) + ]: + im = Image.new("P", (100, 100), color) + expected = Image.new(mode, (100, 100), color) + self.assert_image_equal(im.convert(mode), expected) + def test_no_resource_warning_on_save(self): # https://github.com/python-pillow/Pillow/issues/835 # Arrange diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 51d6e8466..607522023 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -2374,7 +2374,14 @@ def new(mode, size, color=0): from . import ImageColor color = ImageColor.getcolor(color, mode) - return Image()._new(core.fill(mode, size, color)) + im = Image() + if mode == "P" and \ + isinstance(color, (list, tuple)) and len(color) in [3, 4]: + # RGB or RGBA value for a P image + from . import ImagePalette + im.palette = ImagePalette.ImagePalette() + color = im.palette.getcolor(color) + return im._new(core.fill(mode, size, color)) def frombytes(mode, size, data, decoder_name="raw", *args):