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

标签 python transparency python-imaging-library imaging

我有两个相同大小的 png 图像(A 和 B),第二个 (B) 是部分透明的。

如果我使用代码将图像 B 粘贴到图像 A 中

base.paste(overlay, mask=overlay)

我得到了它们近乎完美的组合。

但我想在将图像 B 粘贴到图像 A 之前将其变亮。我尝试使用像 Image.new("L", size, 80) 这样的蒙版,我可以用它来照亮图像 (B),但它也使图像 (A) 变暗并且不得修改。

在命令行上,我可以像这样使用 ImageMagick 做我想做的事:

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

这正是我所需要的,但我如何使用 python 做到这一点。

最佳答案

根据我自己的理解,溶解选项仅修改 alpha channel 。因此,如果您希望您的 alpha channel 仅保留其值的 40%,您可以在 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 channel 。因此,我只需将其值乘以 0.4 (40%),然后创建一个新图像以粘贴到基础图像上。

关于 python (PIL) : Lighten transparent image and paste to another one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13662184/

相关文章:

jquery - 通过 jquery 提交表单后 Flask 重定向不起作用

c# - 如何使用 Mono 在 GTK# TextView 中设置透明背景?

video - 透明地将 mp4 转换为 webm?

python - 在不加载图像的情况下从 python 获取图像文件的形状

python - 在opencv中用拉普拉斯算子的方差计算模糊度

python - TimeoutError : QueuePool limit of size 5 overflow 10 reached, 连接超时,超时30

transparency - 如何在opencv-python中创建透明掩码

python - 如何使用 ImageDraw 模糊椭圆

python-2.7 - IO错误:Cannot open image while generating barcode after freezing using py2exe

c# - Azure 表存储多行查询性能