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