【问题标题】:Vertically fade an image with transparent background to transparency using Python PIL library使用 Python PIL 库将具有透明背景的图像垂直淡化为透明度
【发布时间】:2017-04-18 08:07:09
【问题描述】:

所以我想淡出已经有透明背景的图像。

我在this question 中找到了不透明图像的解决方案,但它不适用于具有透明背景的图像。那么如何将具有透明背景的图像垂直淡化为透明呢?

例如,我希望这张图片变成这张,仍然有透明背景。

这是我用来创建透明图像的代码

bg = Image.new("RGBA", (width, height), (r,g,b,inputBgAlpha))
...
bg.paste(deviceBg, devicePadding, mask=deviceBg)

以下是我尝试过的。它会产生带颜色而不是透明的背景。

# https://stackoverflow.com/a/19236775/2603230
arr = numpy.array(bg)
alpha = arr[:, :, 3]
n = len(alpha)
alpha[:] = numpy.interp(numpy.arange(n), [0, 0.55*n, 0.05*n, n], [255, 255, 0, 0])[:,numpy.newaxis]
bg = Image.fromarray(arr, mode='RGBA')

【问题讨论】:

    标签: python png python-imaging-library transparency


    【解决方案1】:

    对代码 here 稍作改动就可以让它工作 :)

    from PIL import Image
    
    im = Image.open('bird.jpg')
    width, height = im.size
    pixels = im.load()
    for y in range(int(height*.55), int(height*.75)):
        for x in range(width):
            alpha = pixels[x, y][3]-int((y - height*.55)/height/.20 * 255)
            if alpha <= 0:
                alpha = 0
            pixels[x, y] = pixels[x, y][:3] + (alpha,)
    for y in range(y, height):
        for x in range(width):
            pixels[x, y] = pixels[x, y][:3] + (0,)
    bg.save('birdfade.png')
    

    【讨论】:

      猜你喜欢
      • 2013-10-14
      • 2012-09-21
      • 1970-01-01
      • 2012-05-26
      • 2015-05-15
      • 1970-01-01
      • 2011-12-05
      • 1970-01-01
      • 2015-01-20
      相关资源
      最近更新 更多