如何使用 python pil 创建不同的透明度,如渐变?

How to create different transparency like gradient with python pil?

我可以用 python 枕头做这样的事情吗?不知道怎么形容。

更新答案

这比我原来的答案更简单:

#!/usr/bin/env python3

from PIL import Image

# Define width and height
w, h = 400, 200

# Make solid orange background
im = Image.new('RGB', (w,h), 'orange')

# Build an alpha/transparency channel
alpha = Image.linear_gradient('L').rotate(-90).resize((w,h))
alpha.save('DEBUG-alpha.png')

# Put our lovely new alpha channel into orange image
im.putalpha(alpha)
im.save('result.png')

Alpha 通道的外观如下 - 我添加了红色边框,因此您可以在任何背景上看到它的范围:

如果你想改变橙色和透明度之间的滚降率,你可以这样做:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Define width and height
w, h = 400, 200

# Make solid orange background
im = Image.new('RGB', (w,h), 'orange')

# Build an alpha/transparency channel
alpha = Image.linear_gradient('L').rotate(-90).resize((w,h))

# Optional gamma adjustment. Smaller gamma makes image darker, bigger gamma makes it brighter
gamma = 0.4
alpha = alpha.point(lambda f: int((f/255.0)**(1/gamma)*255))
alpha.save('DEBUG-alpha.png')

# Put our lovely new alpha channel into orange image
im.putalpha(alpha)
im.save('result.png')

原答案

你可以这样做:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Define width and height
w, h = 400, 200

# Make solid orange background
im = Image.new('RGB', (w,h), 'orange')

# Build an alpha/transparency channel
# ... make one line w pixels wide, going from 255..0
line = np.linspace(255,0, num=w, dtype=np.uint8)
# ... repeat that line h times to get the full height of the image
alpha = np.tile(line, (h,1))

# Put our lovely new alpha channel into orange image
im.putalpha(Image.fromarray(alpha))

im.save('result.png')