使用Python PIL库将透明背景的图像垂直淡化为透明度

时间:2016-12-03 14:17:28

标签: python png python-imaging-library transparency

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

我在this question找到了非透明图片的解决方案,但它对透明背景的图片不起作用。那么如何将透明背景的图像垂直淡化为透明度呢?

例如,我希望old image此图片变为new image,此图片仍具有透明背景。

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

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

以下是我的尝试。它导致背景颜色而不是transprent。

# 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')

1 个答案:

答案 0 :(得分:0)

代码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')