3

I have two png-images (A & B) of the same size, the second (B) one is partially transparent.

If I paste image B into image A using the code

base.paste(overlay, mask=overlay)

I get a nearly perfect combination of them.

But I want to lighten image B before pasting it into image A. I have tried using a mask like Image.new("L", size, 80) and I can lighten image (B) with it, but it also darkens image (A) and that must not modified.

On the command line, I can do what I want with ImageMagick like that:

composite -dissolve 40 overlay.png base.png result.png

That is exactly what I need, but how can I do this with python.

t777
  • 3,099
  • 8
  • 35
  • 53

1 Answers1

5

From my own understanding, the dissolve option modifies only the alpha channel. So, if you want your alpha channel to keep only 40% of its values, you do the same in PIL:

from PIL import Image

overlay = Image.open('overlay.png')
base = Image.open('base.png')

bands = list(overlay.split())
if len(bands) == 4:
    # Assuming alpha is the last band
    bands[3] = bands[3].point(lambda x: x*0.4)
overlay = Image.merge(overlay.mode, bands)

base.paste(overlay, (0, 0), overlay)
base.save('result.png')

In this code, I split the image in multiple bands. If there are four of them, I assume the last one represents the alpha channel. So I simply multiply by 0.4 (40%) its values, and create a new image to be pasted over the base image.

mmgp
  • 18,901
  • 3
  • 53
  • 80
  • Thanks a lot. I have to convert both images to "RGBA" and then I get the same result as with the above mentioned imagemagick-command. Thanks again!!! – t777 Dec 10 '12 at 22:23
  • I have experimted a little bit and I get the best result, if I use the original overlay-image as the first argument in the paste-method and the modified overlay-image as the mask: `base.paste(overlay, mask=mask)` – t777 Dec 29 '12 at 19:54