I need to add transparent gradient to an image like on the image below , I tried this:
def test(path):
im = Image.open(path)
if im.mode != 'RGBA':
im = im.convert('RGBA')
width, height = im.size
gradient = Image.new('L', (width, 1), color=0xFF)
for x in range(width):
gradient.putpixel((0 + x, 0), x)
alpha = gradient.resize(im.size)
im.putalpha(alpha)
im.save('out.png', 'PNG')
But with this I added only white gradient. How can I change color of gradient and control size of gradient.
I need like the following but without text.
解决方案
Your code actually does what it says it does. However, if your image background is not black but white, then the image will appear lighter. The following code merges the original image with a black image, such that you have the dark gradient effect irrespective of background.
def test(path):
im = Image.open(path)
if im.mode != 'RGBA':
im = im.convert('RGBA')
width, height = im.size
gradient = Image.new('L', (width, 1), color=0xFF)
for x in range(width):
gradient.putpixel((x, 0), 255-x)
alpha = gradient.resize(im.size)
black_im = Image.new('RGBA', (width, height), color=0) # i.e. black
black_im.putalpha(alpha)
gradient_im = Image.alpha_composite(im, black_im)
gradient_im.save('out.png', 'PNG')
EDIT
There are different ways to scale the gradient. Below is one suggestion.
def test(path, gradient_magnitude=1.):
im = Image.open(path)
if im.mode != 'RGBA':
im = im.convert('RGBA')
width, height = im.size
gradient = Image.new('L', (width, 1), color=0xFF)
for x in range(width):
# gradient.putpixel((x, 0), 255-x)
gradient.putpixel((x, 0), int(255 * (1 - gradient_magnitude * float(x)/width)))
alpha = gradient.resize(im.size)
black_im = Image.new('RGBA', (width, height), color=0) # i.e. black
black_im.putalpha(alpha)
gradient_im = Image.alpha_composite(im, black_im)
gradient_im.save('out.png', 'PNG')