python图片背景透明软件,使用Python PIL库将具有透明背景的图像垂直淡化为透明...

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 xApF1.png this image become aee87538beffd9d4bff0f254f9bbc565.png 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')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值