Skip to content

Commit

Permalink
do not premultiply alpha when resizing with Image.NEAREST resampling
Browse files Browse the repository at this point in the history
  • Loading branch information
nulano committed Mar 3, 2021
1 parent 4b73397 commit 87d8571
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
40 changes: 40 additions & 0 deletions Tests/test_image_transform.py
Expand Up @@ -143,6 +143,46 @@ def op(im, sz):

self._test_alpha_premult(op)

def _test_nearest(self, op, mode):
# create white image with half transparent,
# with the black half transparent.
# do op,
# the image should be white with half transparent
if mode == "RGBA":
transparent = (255, 255, 255, 0)
opaque = (255, 255, 255, 255)
elif mode == "LA":
transparent = (255, 0)
opaque = (255, 255)
else:
assert False, "bad test"
im = Image.new(mode, (10, 10), transparent)
im2 = Image.new(mode, (5, 10), opaque)
im.paste(im2, (0, 0))

im = op(im, (40, 10))

colors = im.getcolors()
assert colors == [
(20 * 10, opaque),
(20 * 10, transparent),
]

@pytest.mark.parametrize("mode", ("RGBA", "LA"))
def test_nearest_resize(self, mode):
def op(im, sz):
return im.resize(sz, Image.NEAREST)

self._test_nearest(op, mode)

@pytest.mark.parametrize("mode", ("RGBA", "LA"))
def test_nearest_transform(self, mode):
def op(im, sz):
(w, h) = im.size
return im.transform(sz, Image.EXTENT, (0, 0, w, h), Image.NEAREST)

self._test_nearest(op, mode)

def test_blank_fill(self):
# attempting to hit
# https://github.com/python-pillow/Pillow/issues/254 reported
Expand Down
6 changes: 3 additions & 3 deletions src/PIL/Image.py
Expand Up @@ -1912,7 +1912,7 @@ def resize(self, size, resample=BICUBIC, box=None, reducing_gap=None):
if self.mode in ("1", "P"):
resample = NEAREST

if self.mode in ["LA", "RGBA"]:
if self.mode in ["LA", "RGBA"] and resample != NEAREST:
im = self.convert(self.mode[:-1] + "a")
im = im.resize(size, resample, box)
return im.convert(self.mode)
Expand Down Expand Up @@ -2396,14 +2396,14 @@ def getdata(self):
:returns: An :py:class:`~PIL.Image.Image` object.
"""

if self.mode == "LA":
if self.mode == "LA" and resample != NEAREST:
return (
self.convert("La")
.transform(size, method, data, resample, fill, fillcolor)
.convert("LA")
)

if self.mode == "RGBA":
if self.mode == "RGBA" and resample != NEAREST:
return (
self.convert("RGBa")
.transform(size, method, data, resample, fill, fillcolor)
Expand Down

0 comments on commit 87d8571

Please sign in to comment.