Pillow icon indicating copy to clipboard operation
Pillow copied to clipboard

If pasting an image onto itself at a lower position, copy from bottom

Open radarhere opened this issue 8 months ago • 2 comments

Resolves #8881

When pasting an image, https://github.com/python-pillow/Pillow/blob/c8d98d56a02e0729f794546d6f270b3cea5baecf/src/libImaging/Paste.c#L47-L49 will copy the rows of the image from top to bottom.

However, if the image is pasting onto itself, but say, 10 pixels lower, after those 10 rows, it will start reading from a part of the image that has already been written to. This results in a repeating effect.

from PIL import Image
im = Image.open("Tests/images/hopper.png")
im.paste(im, (0, 10))

repeat

A solution for that situation is to instead copy the rows of the image from bottom to top.

copy

radarhere avatar Apr 11 '25 12:04 radarhere

It seems there is a different C-code that is called if a mask is available. Maybe your fix works here, too. Have you tested it with a mask?

mask = Image.new("1", img.size, 1) # mask without an effect just to make sure that also the mask is tested

img.paste(
    img,
    box=(0, 10),
    mask=mask,
)
img.save("img_pasted.png")

ghost avatar Apr 11 '25 15:04 ghost

Ok, I've pushed a commit to cover masks as well.

radarhere avatar Apr 11 '25 22:04 radarhere