繁体   English   中英

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

[英]Vertically fade an image with transparent background to transparency using Python PIL library

因此,我想淡出已经具有透明背景的图像。

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

例如,我想要 旧形象 该图像成为 新图片 这个,仍然有透明的背景。

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

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

这里对代码进行一些更改可以使其起作用:)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM