简体   繁体   中英

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

So I would like to fade out an image which already had an transparent background.

I've found solution for non-transparent image in this question , but it does not work for the image with transparent background. So how can I do to vertically fade an image with transparent background to transparency?

For example, I want 旧形象 this image become 新图片 this one, which still have transparent background.

Here is the code I used to create the transparent image

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

And the following is what I tried. It results in a background with color instead of 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')

A little change on code here can make it works :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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