PIL:使图像按百分比比例透明

时间:2018-06-21 08:11:23

标签: python python-imaging-library

如何使watermark图像透明?例如,60%透明。我已经尝试过putalpha,但似乎无法正常工作

from PIL import Image


temp_image = Image.open('test1.jpg')
watermark = Image.open('watermark.png')

x, y = temp_image.size

image_with_watermark = Image.new('RGBA', (x, y), (0, 0, 0, 0))
image_with_watermark.paste(temp_image, (0, 0))
image_with_watermark.paste(watermark, (0, 0), mask=watermark)
image_with_watermark.show()

编辑:

好的,这可行,需要弄清楚如何使用%

进行设置
from PIL import Image


temp_image = Image.open('test1.jpg')
watermark = Image.open('watermark.png')

x, y = temp_image.size

watermask = watermark.convert("L").point(lambda x: min(x, 50))
watermark.putalpha(watermask)

image_with_watermark = Image.new('RGBA', (x, y), (0, 0, 0, 0))
image_with_watermark.paste(temp_image, (0, 0))
image_with_watermark.paste(watermark, (0, 0), mask=watermark)
image_with_watermark.show()

嗯,在以下情况下水印的质量很低:

watermask = watermark.convert("L").point(lambda x: min(x, 50))
watermark.putalpha(watermask)

实现我所需的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

这是一种适用于RGB和RGBA水印图像的解决方案:

from PIL import Image

TRANSPARENCY = 65       # percentage

temp_image = Image.open('test1.jpg')
watermark = Image.open('watermark.png')    

if watermark.mode!='RGBA':
    alpha = Image.new('L', watermark.size, 255)
    watermark.putalpha(alpha)

paste_mask = watermark.split()[3].point(lambda i: i * TRANSPARENCY / 100.)
temp_image.paste(watermark, (0,0), mask=paste_mask)
temp_image.save('res.png')

示例图片(作者-Neil Howard):

Singapore

样本水印(背景是透明的):

Stack Overflow caption

抽样结果:

Singapore + Stack Overflow watermark