python 一张图像叠加半透明_Python(PIL):加亮透明图像并粘贴到另一图像上

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值