问题描述
我有两个大小相同的png图像(A和B),第二个(B)是部分透明的.
I have two png-images (A & B) of the same size, the second (B) one is partially transparent.
如果我使用代码将图像B粘贴到图像A中
If I paste image B into image A using the code
base.paste(overlay, mask=overlay)
我得到了它们的近乎完美的组合.
I get a nearly perfect combination of them.
但是我想在将图像B粘贴到图像A之前使其变亮.我尝试使用像Image.new("L",size,80)这样的蒙版,并且可以使用它使图像(B)变亮,但是它也可以使图像(A)变暗,并且不能修改.
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.
在命令行上,我可以像这样用ImageMagick来做我想做的事情:
On the command line, I can do what I want with ImageMagick like that:
composite -dissolve 40 overlay.png base.png result.png
这正是我所需要的,但是我该如何用python做到这一点.
That is exactly what I need, but how can I do this with python.
推荐答案
根据我的理解,dissolve选项仅修改alpha通道.因此,如果您希望Alpha通道仅保留其值的40%,则可以在PIL中执行相同的操作:
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')
在这段代码中,我将图像分成多个波段.如果有四个,我假设最后一个代表Alpha通道.因此,我只需将其值乘以0.4(40%),然后创建一个新图像粘贴到基本图像上即可.
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.
这篇关于Python(PIL):加亮透明图像并粘贴到另一图像上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!