Skip to content

Commit

Permalink
Merge pull request #1 from radarhere/fix-padding
Browse files Browse the repository at this point in the history
Improved palette handling in ImageOps
  • Loading branch information
PososikTeam committed Sep 19, 2022
2 parents d88200e + 3c42b27 commit 597dff7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
15 changes: 15 additions & 0 deletions Tests/test_imageops.py
Expand Up @@ -130,6 +130,21 @@ def test_pad():
)


@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():
# Division by zero in equalize if < 255 pixels in image (@PIL163)

Expand Down
12 changes: 5 additions & 7 deletions src/PIL/ImageOps.py
Expand Up @@ -21,7 +21,7 @@
import operator
import re

from . import Image
from . import Image, ImagePalette

#
# helpers
Expand Down Expand Up @@ -291,9 +291,8 @@ def pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5
out = resized
else:
out = Image.new(image.mode, size, color)
palette = image.palette.copy()
if palette:
out.putpalette(palette)
if resized.palette:
out.putpalette(resized.getpalette())
if resized.width != size[0]:
x = int((size[0] - resized.width) * max(0, min(centering[0], 1)))
out.paste(resized, (x, 0))
Expand Down Expand Up @@ -399,9 +398,8 @@ def expand(image, border=0, fill=0):
width = left + image.size[0] + right
height = top + image.size[1] + bottom
color = _color(fill, image.mode)
if image.mode == "P" and image.palette:
image.load()
palette = image.palette.copy()
if image.palette:
palette = ImagePalette.ImagePalette(palette=image.getpalette())
if isinstance(color, tuple):
color = palette.getcolor(color)
else:
Expand Down

0 comments on commit 597dff7

Please sign in to comment.