pil对图像加透明 python,使用Python PIL库将图像垂直淡化为透明

I have looked at tutorials, other stackoverflow questions and the PIL documentation itself, but I'm still still not sure how to do it.

I'd like to start fading an image vertically at approximately 55% down the y-axis, and have the image completely transparent at approximately 75%. It's important that I preserve the full height of the image, even though the last 25% or so should be completely transparent.

Is this possible to do with PIL?

解决方案

Sure it's doable.

Let's assume that you're starting off with an image with no transparency (because otherwise, your question is ambiguous).

Step 1: Add an alpha plane. That's just putalpha, unless you're dealing with a non-planar image, in which case you'll need to convert it to RGB or L first.

Step 2: Iterate through the pixels you want to change by using the pixel array returned by load (or getpixel and setpixel if you have to deal with ancient versions of PIL).

Step 3: There is no step 3. Unless you count saving the image. In which case, OK, step 3 is saving the image.

from PIL import Image

im = Image.open('bird.jpg')

im.putalpha(255)

width, height = im.size

pixels = im.load()

for y in range(int(height*.55), int(height*.75)):

alpha = 255-int((y - height*.55)/height/.20 * 255)

for x in range(width):

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

im.save('birdfade.png')

Here the alpha drops off linearly from 255 to 0; it you want it to drop off according to a different curve, or you're using RGB16 instead of RGB8, or you're using L instead of RGB, you should be able to figure out how to change it.

If you want to do this faster, you can use numpy instead of a Python loop for step 2. Or you can reverse steps 1 and 2—construct an alpha plane in advance, and apply it all at once by passing it to putalpha instead of 255. Or… Since this took under half a second on the biggest image I had lying around, I'm not too worried about performance, unless you have to do a million of them and you want a faster version.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值