2016-12-03 2 views
0

Donc, je voudrais fondu une image qui avait déjà un arrière-plan transparent.Fondu verticalement une image avec un arrière-plan transparent pour la transparence à l'aide de la bibliothèque Python PIL

J'ai trouvé une solution pour l'image non-transparente dans this question, mais cela ne fonctionne pas pour l'image avec un arrière-plan transparent. Alors, comment puis-je faire pour fondre verticalement une image avec un fond transparent à la transparence?

Par exemple, je veux old image cette image devient new image celle-ci, qui a toujours un fond transparent.

Voici le code que j'utilisé pour créer l'image transparente

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

Et voici ce que j'ai essayé. Il en résulte un fond avec la couleur au lieu de 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') 

Répondre

0

Un peu de changement sur le code here peut faire cela fonctionne :)

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