Merge pull request #5615 from radarhere/expand

Fixed ImageOps expand with tuple border on P image
This commit is contained in:
Hugo van Kemenade 2021-07-26 11:33:26 +03:00 committed by GitHub
commit 567fbaf782
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 22 deletions

View File

@ -156,23 +156,31 @@ def test_scale():
assert newimg.size == (25, 25) assert newimg.size == (25, 25)
def test_expand_palette(): @pytest.mark.parametrize("border", (10, (1, 2, 3, 4)))
im = Image.open("Tests/images/p_16.tga") def test_expand_palette(border):
im_expanded = ImageOps.expand(im, 10, (255, 0, 0)) with Image.open("Tests/images/p_16.tga") as im:
im_expanded = ImageOps.expand(im, border, (255, 0, 0))
px = im_expanded.convert("RGB").load() if isinstance(border, int):
for b in range(10): left = top = right = bottom = border
else:
left, top, right, bottom = border
px = im_expanded.convert("RGB").load()
for x in range(im_expanded.width): for x in range(im_expanded.width):
assert px[x, b] == (255, 0, 0) for b in range(top):
assert px[x, im_expanded.height - 1 - b] == (255, 0, 0) assert px[x, b] == (255, 0, 0)
for b in range(bottom):
assert px[x, im_expanded.height - 1 - b] == (255, 0, 0)
for y in range(im_expanded.height): for y in range(im_expanded.height):
assert px[b, x] == (255, 0, 0) for b in range(left):
assert px[b, im_expanded.width - 1 - b] == (255, 0, 0) assert px[b, y] == (255, 0, 0)
for b in range(right):
assert px[im_expanded.width - 1 - b, y] == (255, 0, 0)
im_cropped = im_expanded.crop( im_cropped = im_expanded.crop(
(10, 10, im_expanded.width - 10, im_expanded.height - 10) (left, top, im_expanded.width - right, im_expanded.height - bottom)
) )
assert_image_equal(im_cropped, im) assert_image_equal(im_cropped, im)
def test_colorize_2color(): def test_colorize_2color():

View File

@ -21,7 +21,7 @@ import functools
import operator import operator
import re import re
from . import Image, ImageDraw from . import Image
# #
# helpers # helpers
@ -395,15 +395,16 @@ def expand(image, border=0, fill=0):
height = top + image.size[1] + bottom height = top + image.size[1] + bottom
color = _color(fill, image.mode) color = _color(fill, image.mode)
if image.mode == "P" and image.palette: if image.mode == "P" and image.palette:
out = Image.new(image.mode, (width, height)) image.load()
out.putpalette(image.palette) palette = image.palette.copy()
out.paste(image, (left, top)) if isinstance(color, tuple):
color = palette.getcolor(color)
draw = ImageDraw.Draw(out)
draw.rectangle((0, 0, width - 1, height - 1), outline=color, width=border)
else: else:
out = Image.new(image.mode, (width, height), color) palette = None
out.paste(image, (left, top)) out = Image.new(image.mode, (width, height), color)
if palette:
out.putpalette(palette.palette)
out.paste(image, (left, top))
return out return out