Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions Tests/test_image_paste.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,74 @@ def test_color_mask_RGBa(self, mode: str) -> None:
],
)

@staticmethod
def _alpha_mask(mask_mode: str) -> Image.Image:
mask = Image.new(mask_mode, (2, 1))
for x, alpha in enumerate((255, 51)):
mask.putpixel((x, 0), (0,) * (len(mask_mode) - 1) + (alpha,))
return mask

@pytest.mark.parametrize("mode", ("I;16", "I;16L", "I;16B", "I;16N", "I", "F"))
@pytest.mark.parametrize("mask_mode", ("L", "LA", "RGBA", "RGBa"))
def test_image_mask_wide_modes(self, mode: str, mask_mode: str) -> None:
im = Image.new(mode, (2, 1), 1000)
im.paste(Image.new(mode, (2, 1), 3000), (0, 0), self._alpha_mask(mask_mode))

# 51 / 255 = 20% of the source, RGBa expects a premultiplied source
expected = 3800 if mask_mode == "RGBa" else 1400
assert im.getpixel((0, 0)) == 3000
assert im.getpixel((1, 0)) == expected

@pytest.mark.parametrize("mode", ("I;16", "I;16L", "I;16B", "I;16N", "I", "F"))
@pytest.mark.parametrize("mask_mode", ("L", "RGBA", "RGBa"))
def test_color_mask_wide_modes(self, mode: str, mask_mode: str) -> None:
im = Image.new(mode, (2, 1), 1000)
im.paste(3000, (0, 0, 2, 1), self._alpha_mask(mask_mode))

expected = 3800 if mask_mode == "RGBa" else 1400
assert im.getpixel((0, 0)) == 3000
assert im.getpixel((1, 0)) == expected

@pytest.mark.parametrize("value", (float("nan"), float("inf"), float("-inf")))
@pytest.mark.parametrize("mask_mode", ("L", "LA", "RGBA", "RGBa"))
def test_mask_wide_non_finite_ignored(self, mask_mode: str, value: float) -> None:
# Pixel 0 is fully opaque, so the destination is ignored
im = Image.new("F", (2, 1), value)
im.paste(Image.new("F", (2, 1), 2.5), (0, 0), self._alpha_mask(mask_mode))
assert im.getpixel((0, 0)) == 2.5

if mask_mode != "LA":
im = Image.new("F", (2, 1), value)
im.paste(2.5, (0, 0, 2, 1), self._alpha_mask(mask_mode))
assert im.getpixel((0, 0)) == 2.5

if mask_mode == "RGBa":
# A premultiplied source is still added where it is fully transparent
return

# Fully transparent, so the source is ignored
mask = Image.new(mask_mode, (1, 1), (0,) * len(mask_mode))
im = Image.new("F", (1, 1), 1.5)
im.paste(Image.new("F", (1, 1), value), (0, 0), mask)
assert im.getpixel((0, 0)) == 1.5

if mask_mode != "LA":
im.paste(value, (0, 0, 1, 1), mask)
assert im.getpixel((0, 0)) == 1.5

@pytest.mark.parametrize("mode", ("I;16", "I;16L", "I;16B", "I;16N"))
def test_color_i16(self, mode: str) -> None:
im = Image.new(mode, (2, 1), 1000)
im.paste(3000, (0, 0, 1, 1))
assert im.getpixel((0, 0)) == 3000
assert im.getpixel((1, 0)) == 1000

mask = Image.new("1", (2, 1))
mask.putpixel((1, 0), 1)
im.paste(4660, (0, 0, 2, 1), mask)
assert im.getpixel((0, 0)) == 3000
assert im.getpixel((1, 0)) == 4660

def test_different_sizes(self) -> None:
im = Image.new("RGB", (100, 100))
im2 = Image.new("RGB", (50, 50))
Expand Down
9 changes: 9 additions & 0 deletions docs/releasenotes/13.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,15 @@ On little-endian systems, :py:meth:`~PIL.Image.Image.resize` read and wrote
I;16B and I;16N pixel values in the wrong byte order when using a resampling
filter other than ``Resampling.NEAREST``. This has been fixed.

Pasting into I;16, I and F images
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

:py:meth:`~PIL.Image.Image.paste` with an L, LA, RGBA or RGBa mask blended
each byte of an I;16, I or F pixel separately, so partly transparent pixels
received unrelated values. Pasting a color into an I;16 image without a mask
or with a 1 mask also wrote the wrong value. Pixels are now blended as whole
values, in the byte order of the mode.

Blurring I;16 images
^^^^^^^^^^^^^^^^^^^^

Expand Down
229 changes: 200 additions & 29 deletions src/libImaging/Paste.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@

#include "Imaging.h"

#include <math.h>

#define PREPARE_PASTE_LOOP() \
int y, y_end, offset; \
if (imOut == imIn && dy > sy) { \
Expand Down Expand Up @@ -296,6 +298,119 @@ paste_mask_RGBa(
}
}

/*
* I;16, I and F pixels are single numbers wider than a byte. Blending them
* with a mask has to work on the whole value, not on each of its bytes.
*/
static inline int
i16_bigendian(Imaging im) {
return im->mode == IMAGING_MODE_I_16B
#ifdef WORDS_BIGENDIAN
|| im->mode == IMAGING_MODE_I_16N
#endif
;
}

static inline double
get_wide(Imaging im, const UINT8 *p) {
INT32 i;
FLOAT32 f;
switch (im->type) {
case IMAGING_TYPE_I16:
return i16_bigendian(im) ? (p[0] << 8) + p[1] : p[0] + (p[1] << 8);
case IMAGING_TYPE_INT32:
memcpy(&i, p, sizeof(i));
return i;
default:
memcpy(&f, p, sizeof(f));
return f;
}
}

static inline void
put_wide(Imaging im, UINT8 *p, double v) {
INT32 i;
FLOAT32 f;
switch (im->type) {
case IMAGING_TYPE_I16:
i = v <= 0.0 ? 0 : v >= 65535.0 ? 65535 : (INT32)(v + 0.5);
if (i16_bigendian(im)) {
p[0] = (UINT8)(i >> 8);
p[1] = (UINT8)i;
} else {
p[0] = (UINT8)i;
p[1] = (UINT8)(i >> 8);
}
break;
case IMAGING_TYPE_INT32:
v = floor(v + 0.5);
i = v <= INT32_MIN ? INT32_MIN : v >= INT32_MAX ? INT32_MAX : (INT32)v;
memcpy(p, &i, sizeof(i));
break;
default:
f = (FLOAT32)v;
memcpy(p, &f, sizeof(f));
break;
}
}

static inline double
blend_wide(double out, double in, UINT8 a, int premultiplied) {
/* return the side that is used as it is, so that a NaN or infinity on
the ignored side does not leak through a multiplication by zero */
if (a == 255) {
return in;
}
if (a == 0 && !premultiplied) {
return out;
}
if (premultiplied) {
return in + out * (255 - a) / 255.0;
}
return (in * a + out * (255 - a)) / 255.0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this preserve the fully transparent / fully opaque cases when an F pixel is NaN or infinity? Multiplying the ignored value by zero still produces NaN:

from PIL import Image

dst = Image.new("F", (1, 1), 1.5)
src = Image.new("F", (1, 1), float("nan"))
dst.paste(src, (0, 0), Image.new("L", (1, 1), 0))
print(dst.getpixel((0, 0)))  # base: 1.5; this PR: nan

The reverse also occurs with a NaN destination, finite source and mask 255; infinity produces the same result. I reproduced both image and scalar-color pastes on Windows/Python 3.12, comparing 0634558 with its parent 86399b1. The PR's 42 wide-mode tests and both builds' selftests passed. These were in-memory tests; the local builds had JPEG and zlib disabled.

Would short-circuiting the L-mask endpoints before the arithmetic be appropriate? Tests with non-finite values on the ignored side would catch this.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for catching this! Fixed in ba533da.

blend_wide() now returns the source as it is when alpha is 255, and the destination as it is when alpha is 0 (L, LA and RGBA masks), before any arithmetic. With an RGBa mask, alpha 0 still adds the premultiplied source like PREBLEND, so only the opaque end is short-circuited there. This covers both image and color pastes.

Added test_mask_wide_non_finite_ignored, with NaN, inf and -inf on the ignored side for each mask mode; it fails on 0634558 and passes now. Tests/test_image_paste.py passes (115), and the full suite shows no new failures compared to 0634558 (my local build has zlib and JPEG disabled, so those tests fail on both). ruff, black and clang-format are clean.

}

static inline void
paste_mask_wide(
Imaging imOut,
Imaging imIn,
Imaging imMask,
int dx,
int dy,
int sx,
int sy,
int xsize,
int ysize,
int pixelsize
) {
/* paste an I;16, I or F image with mode "L", "LA", "RGBA" or "RGBa" matte */

int x;
/* the alpha is the only band of "L", and the last of the other modes */
int mask_step = imMask->mode == IMAGING_MODE_L ? 1 : 4;
int mask_offset = mask_step - 1;
int premultiplied = imMask->mode == IMAGING_MODE_RGBa;

PREPARE_PASTE_LOOP();
for (; y != y_end; y += offset) {
UINT8 *out = (UINT8 *)imOut->image[y + dy] + dx * pixelsize;
UINT8 *in = (UINT8 *)imIn->image[y + sy] + sx * pixelsize;
UINT8 *mask = (UINT8 *)imMask->image[y + sy] + sx * mask_step + mask_offset;
for (x = 0; x < xsize; x++) {
put_wide(
imOut,
out,
blend_wide(
get_wide(imOut, out), get_wide(imIn, in), *mask, premultiplied
)
);
out += pixelsize;
in += pixelsize;
mask += mask_step;
}
}
}

int
ImagingPaste(
Imaging imOut, Imaging imIn, Imaging imMask, int dx0, int dy0, int dx1, int dy1
Expand Down Expand Up @@ -352,6 +467,16 @@ ImagingPaste(
ImagingSectionEnter(&cookie);
paste_mask_1(imOut, imIn, imMask, dx0, dy0, sx0, sy0, xsize, ysize, pixelsize);
ImagingSectionLeave(&cookie);
} else if (
imOut->type != IMAGING_TYPE_UINT8 &&
(imMask->mode == IMAGING_MODE_L || imMask->mode == IMAGING_MODE_LA ||
imMask->mode == IMAGING_MODE_RGBA || imMask->mode == IMAGING_MODE_RGBa)
) {
ImagingSectionEnter(&cookie);
paste_mask_wide(
imOut, imIn, imMask, dx0, dy0, sx0, sy0, xsize, ysize, pixelsize
);
ImagingSectionLeave(&cookie);
} else if (imMask->mode == IMAGING_MODE_L) {
ImagingSectionEnter(&cookie);
paste_mask_L(imOut, imIn, imMask, dx0, dy0, sx0, sy0, xsize, ysize, pixelsize);
Expand Down Expand Up @@ -383,34 +508,30 @@ fill(
/* fill opaque region */

int x, y;
UINT8 ink8 = 0;
INT32 ink32 = 0L;

memcpy(&ink32, ink, pixelsize);
memcpy(&ink8, ink, sizeof(ink8));

if (imOut->image8 || ink32 == 0L) {
int i16 = imOut->type == IMAGING_TYPE_I16;
if (i16 && ink32 != 0L) {
for (y = 0; y < ysize; y++) {
UINT16 *out = (UINT16 *)imOut->image[y + dy] + dx;
for (x = 0; x < xsize; x++) {
*out++ =
#ifdef WORDS_BIGENDIAN
(ink[0] << 8) | ink[1];
#else
ink[0] | (ink[1] << 8);
#endif
}
}
} else {
UINT8 ink8 = 0;
memcpy(&ink8, ink, sizeof(ink8));
if (pixelsize == 1 || ink32 == 0L) {
dx *= pixelsize;
xsize *= pixelsize;
for (y = 0; y < ysize; y++) {
memset(imOut->image[y + dy] + dx, ink8, xsize);
}

dx *= pixelsize;
xsize *= pixelsize;
for (y = 0; y < ysize; y++) {
memset(imOut->image[y + dy] + dx, ink8, xsize);
} else if (imOut->image8) {
/* I;16: copy the ink bytes as they are (ImagingFill2 already
swapped them into the mode's byte order). */
dx *= pixelsize;
for (y = 0; y < ysize; y++) {
UINT8 *out = (UINT8 *)imOut->image[y + dy] + dx;
for (x = 0; x < xsize; x++, out += pixelsize) {
memcpy(out, ink, pixelsize);
}
}

} else {
#if defined _WIN32 && !defined _WIN64
int i;
Expand Down Expand Up @@ -504,19 +625,11 @@ fill_mask_L(
unsigned int tmp1;

if (imOut->image8) {
int i16 = imOut->type == IMAGING_TYPE_I16;
for (y = 0; y < ysize; y++) {
UINT8 *out = imOut->image8[y + dy] + dx;
if (i16) {
out += dx;
}
UINT8 *mask = imMask->image8[y + sy] + sx;
for (x = 0; x < xsize; x++) {
*out = BLEND(*mask, *out, ink[0], tmp1);
if (i16) {
out++;
*out = BLEND(*mask, *out, ink[1], tmp1);
}
out++, mask++;
}
}
Expand Down Expand Up @@ -637,6 +750,42 @@ fill_mask_RGBa(
}
}

static inline void
fill_mask_wide(
Imaging imOut,
const UINT8 *ink,
Imaging imMask,
int dx,
int dy,
int sx,
int sy,
int xsize,
int ysize,
int pixelsize
) {
/* fill an I;16, I or F image with mode "L", "RGBA" or "RGBa" matte */

int x, y;
int mask_step = imMask->mode == IMAGING_MODE_L ? 1 : 4;
int mask_offset = mask_step - 1;
int premultiplied = imMask->mode == IMAGING_MODE_RGBa;
double value = get_wide(imOut, ink);

for (y = 0; y < ysize; y++) {
UINT8 *out = (UINT8 *)imOut->image[y + dy] + dx * pixelsize;
UINT8 *mask = (UINT8 *)imMask->image[y + sy] + sx * mask_step + mask_offset;
for (x = 0; x < xsize; x++) {
put_wide(
imOut,
out,
blend_wide(get_wide(imOut, out), value, *mask, premultiplied)
);
out += pixelsize;
mask += mask_step;
}
}
}

int
ImagingFill2(
Imaging imOut, const void *ink, Imaging imMask, int dx0, int dy0, int dx1, int dy1
Expand All @@ -653,6 +802,20 @@ ImagingFill2(

pixelsize = imOut->pixelsize;

UINT8 ink16[4] = {0};
if (imOut->type == IMAGING_TYPE_I16) {
/* getink() gives I;16 ink in little endian order, whatever the mode */
const UINT8 *ink8 = ink;
if (i16_bigendian(imOut)) {
ink16[0] = ink8[1];
ink16[1] = ink8[0];
} else {
ink16[0] = ink8[0];
ink16[1] = ink8[1];
}
ink = ink16;
}

xsize = (int64_t)dx1 - dx0;
ysize = (int64_t)dy1 - dy0;

Expand Down Expand Up @@ -696,6 +859,14 @@ ImagingFill2(
ImagingSectionEnter(&cookie);
fill_mask_1(imOut, ink, imMask, dx0, dy0, sx0, sy0, xsize, ysize, pixelsize);
ImagingSectionLeave(&cookie);
} else if (
imOut->type != IMAGING_TYPE_UINT8 &&
(imMask->mode == IMAGING_MODE_L || imMask->mode == IMAGING_MODE_RGBA ||
imMask->mode == IMAGING_MODE_RGBa)
) {
ImagingSectionEnter(&cookie);
fill_mask_wide(imOut, ink, imMask, dx0, dy0, sx0, sy0, xsize, ysize, pixelsize);
ImagingSectionLeave(&cookie);
} else if (imMask->mode == IMAGING_MODE_L) {
ImagingSectionEnter(&cookie);
fill_mask_L(imOut, ink, imMask, dx0, dy0, sx0, sy0, xsize, ysize, pixelsize);
Expand Down