8

I need to blend an image over another image using Pythons PIL Library.

As you can see in the image below, my two source images are A and B. When I do:

imageA.paste(imageB, (0, 0), imageB)

I get C as a result, but the part at the top of the gray background is now transparent. Image D is what I get when I put B over A in Photoshop and is what I need to achieve with PIL.

What am I doing wrong? How can I compose B over A in PIL to get D instead of C?

Example Image

Daniela
  • 169
  • 2
  • 5
  • what happens with: `imageA.paste(imageB, (0, 0), mask=imageB)` – RickyA Jul 03 '14 at 09:15
  • @RickyA That should be exactly the same: the third argument to `paste` *is* the mask. Try using `imageA` as the mask instead: `imageA.paste(imageB, (0, 0), imageA)` – Germano Jul 03 '14 at 09:30
  • @Germano: That doesn't work either, image B has a drop shadow that would be cut off if I do that. – Daniela Jul 03 '14 at 10:46
  • 9
    Don't use PIL, use Pillow. See http://stackoverflow.com/a/15919897/5987 – Mark Ransom Jul 03 '14 at 14:48
  • I can't reproduce this problem. When I run `imageA.paste(imageB, (0, 0), imageB)` on some test png files it produces something similar to D. Could you post your source images (A & B) along with your full code? – Peter Gibson Oct 14 '14 at 06:09
  • 1
    What modes are the source and mask in ? Try to have them in RGBA mode for blending. –  Nov 19 '14 at 09:58
  • Possible duplicate of http://stackoverflow.com/questions/5324647/how-to-merge-a-transparent-png-image-with-another-image-using-pil – Charles Merriam Aug 24 '15 at 01:28

2 Answers2

3

use RGBA for transparency mask

imageA.paste(imageB, (0, 0), imageB.convert('RGBA'))
autopython
  • 41
  • 4
  • Thank you! This is the best solution! The third parameter is a transparency map, but instead of creating it manually you just created it with PIL. This should be the accepted answer. – gempir Aug 03 '20 at 10:00
1

I can't comment for now (rep constraint).

But I think what you really need, according to your need, is to do this instead:

imageB.paste(imageA, (0, 0), imageA)

Basically, that is, make B the background image to get the desired results, because that's what I see in D.

EDIT: Looking around more, I found this: https://stackoverflow.com/a/15919897/4029893

I think you should definitely use the alpha_composite method, since paste doesn't work as expected for background images with transparency.

Community
  • 1
  • 1
bad_keypoints
  • 1,382
  • 2
  • 23
  • 45