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.
解决方案
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.