试试这个。初始不透明度值为0.9或0.95应该能给你想要的效果。我还重新组织了一下代码,因为之前的代码很混乱。谁写的上一个版本应该被告诉离电脑远点。;-)
from PIL import Image
def apply_black_gradient(path_in, path_out='out.png',
gradient=1., initial_opacity=1.):
"""
Applies a black gradient to the image, going from left to right.
Arguments:
---------
path_in: string
path to image to apply gradient to
path_out: string (default 'out.png')
path to save result to
gradient: float (default 1.)
gradient of the gradient; should be non-negative;
if gradient = 0., the image is black;
if gradient = 1., the gradient smoothly varies over the full width;
if gradient > 1., the gradient terminates before the end of the width;
initial_opacity: float (default 1.)
scales the initial opacity of the gradient (i.e. on the far left of the image);
should be between 0. and 1.; values between 0.9-1. give good results
"""
input_im = Image.open(path_in)
if input_im.mode != 'RGBA':
input_im = input_im.convert('RGBA')
width, height = input_im.size
alpha_gradient = Image.new('L', (width, 1), color=0xFF)
for x in range(width):
a = int((initial_opacity * 255.) * (1. - gradient * float(x)/width))
if a > 0:
alpha_gradient.putpixel((x, 0), a)
else:
alpha_gradient.putpixel((x, 0), 0)
alpha = alpha_gradient.resize(input_im.size)
black_im = Image.new('RGBA', (width, height), color=0)
black_im.putalpha(alpha)
output_im = Image.alpha_composite(input_im, black_im)
output_im.save(path_out, 'PNG')
return
alpha=0.5
代替alpha = gradient.resize(im.size)
。 - JMat