python 柱形图实现不了渐变_Python枕头:向图像添加透明渐变

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值