【问题标题】:Python3 and Pillow (PIL) - Add an image on top of other image with transparencyPython3 和 Pillow (PIL) - 在具有透明度的其他图像之上添加图像
【发布时间】:2020-10-07 03:52:56
【问题描述】:

我正在创建一个脚本,其中该脚本获取 2 个图像。第一张图片是背景图片,第二张是要显示在第一张图片之上的叠加图片,但透明度几乎为 90%。

我有以下代码:

from PIL import Image
img = Image.open('C:\\Users\\USER\\Desktop\\web\\2.jpg', 'r')
img_w, img_h = img.size

img.putalpha(200)

background = Image.open('C:\\Users\\USER\\Desktop\\web\\email.jpg', 'r')
bg_w, bg_h = background.size
offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2)
background.paste(img, offset)
background.save('C:\\Users\\USER\\Desktop\\out.png')

现在,问题是,img.putalpha(200) 根本没有做任何事情,即使它应该给我图像的透明度。

如何在 Python 中放置叠加图像,然后修改其透明度?

谢谢。

【问题讨论】:

    标签: python-3.x image image-processing python-imaging-library


    【解决方案1】:

    您需要为paste() 添加第三个参数mask

    我使用了这两张图片:

    这是完整的代码:

    #!/usr/bin/env python3
    
    from PIL import Image
    
    # Open overlay image
    img = Image.open('good.jpg')
    img_w, img_h = img.size
    
    img.putalpha(128)
    
    background = Image.open('paddington.jpg')
    bg_w, bg_h = background.size
    offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2)
    background.paste(img, offset, img)
    background.save('result.png')
    

    如果我恢复到原始代码:

    background.paste(img, offset)
    

    【讨论】:

    • 这解决了我的问题!非常感谢!非常感谢:)
    • 酷,很高兴它对你有用。祝你的项目好运!
    猜你喜欢
    • 2021-01-28
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    相关资源
    最近更新 更多