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.