Python (PIL): Lighten transparent image and paste to another one

浪尽此生 提交于 2020-01-14 14:22:45

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/13662184/python-pil-lighten-transparent-image-and-paste-to-another-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!