Set color after attaching palette in expand()

This commit is contained in:
Andrew Murray 2021-06-22 21:21:38 +10:00
parent 8210645e4b
commit b6b362c807
3 changed files with 26 additions and 10 deletions

View File

@ -157,9 +157,16 @@ def test_scale():
def test_expand_palette():
im = Image.open("Tests/images/hopper.gif")
im_expanded = ImageOps.expand(im)
assert_image_equal(im_expanded.convert("RGB"), im.convert("RGB"))
im = Image.open("Tests/images/p_16.tga")
im_expanded = ImageOps.expand(im, 10, (255, 0, 0))
px = im_expanded.convert("RGB").load()
assert px[0, 0] == (255, 0, 0)
im_cropped = im_expanded.crop(
(10, 10, im_expanded.width - 10, im_expanded.height - 10)
)
assert_image_equal(im_cropped, im)
def test_colorize_2color():

View File

@ -20,7 +20,7 @@
import functools
import operator
from . import Image
from . import Image, ImageDraw
#
# helpers
@ -392,10 +392,17 @@ def expand(image, border=0, fill=0):
left, top, right, bottom = _border(border)
width = left + image.size[0] + right
height = top + image.size[1] + bottom
out = Image.new(image.mode, (width, height), _color(fill, image.mode))
color = _color(fill, image.mode)
if image.mode == "P" and image.palette:
out = Image.new(image.mode, (width, height))
out.putpalette(image.palette)
out.paste(image, (left, top))
out.paste(image, (left, top))
draw = ImageDraw.Draw(out)
draw.rectangle((0, 0, width, height), outline=color, width=border)
else:
out = Image.new(image.mode, (width, height), color)
out.paste(image, (left, top))
return out

View File

@ -115,7 +115,7 @@ class ImagePalette:
return self.colors[color]
except KeyError as e:
# allocate new color slot
if isinstance(self.palette, bytes):
if not isinstance(self.palette, bytearray):
self._palette = bytearray(self.palette)
index = len(self.palette) // 3
if index >= 256:
@ -129,9 +129,11 @@ class ImagePalette:
raise ValueError("cannot allocate more than 256 colors") from e
self.colors[color] = index
if index * 3 < len(self.palette):
self._palette[index * 3] = color[0]
self._palette[index * 3 + 1] = color[1]
self._palette[index * 3 + 2] = color[2]
self._palette = (
self.palette[: index * 3]
+ bytes(color)
+ self.palette[index * 3 + 3 :]
)
else:
self._palette += bytes(color)
self.dirty = 1