Merge pull request #6596 from PososikTeam/fix-padding

Improved palette handling in ImageOps
This commit is contained in:
Andrew Murray 2022-09-27 07:27:40 +10:00 committed by GitHub
commit 3fd6a1e312
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 4 deletions

View File

@ -149,6 +149,21 @@ def test_pad_round():
assert new_im.load()[0, 2] == 1 assert new_im.load()[0, 2] == 1
@pytest.mark.parametrize("mode", ("P", "PA"))
def test_palette(mode):
im = hopper(mode)
# Expand
expanded_im = ImageOps.expand(im)
assert_image_equal(im.convert("RGB"), expanded_im.convert("RGB"))
# Pad
padded_im = ImageOps.pad(im, (256, 128), centering=(0, 0))
assert_image_equal(
im.convert("RGB"), padded_im.convert("RGB").crop((0, 0, 128, 128))
)
def test_pil163(): def test_pil163():
# Division by zero in equalize if < 255 pixels in image (@PIL163) # Division by zero in equalize if < 255 pixels in image (@PIL163)

View File

@ -21,7 +21,7 @@ import functools
import operator import operator
import re import re
from . import Image from . import Image, ImagePalette
# #
# helpers # helpers
@ -291,6 +291,8 @@ def pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5
out = resized out = resized
else: else:
out = Image.new(image.mode, size, color) out = Image.new(image.mode, size, color)
if resized.palette:
out.putpalette(resized.getpalette())
if resized.width != size[0]: if resized.width != size[0]:
x = round((size[0] - resized.width) * max(0, min(centering[0], 1))) x = round((size[0] - resized.width) * max(0, min(centering[0], 1)))
out.paste(resized, (x, 0)) out.paste(resized, (x, 0))
@ -396,9 +398,8 @@ def expand(image, border=0, fill=0):
width = left + image.size[0] + right width = left + image.size[0] + right
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.palette:
image.load() palette = ImagePalette.ImagePalette(palette=image.getpalette())
palette = image.palette.copy()
if isinstance(color, tuple): if isinstance(color, tuple):
color = palette.getcolor(color) color = palette.getcolor(color)
else: else: