Python Pillow: Add transparent gradient to an image

[亡魂溺海] 提交于 2020-01-02 22:00:27

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/39842286/python-pillow-add-transparent-gradient-to-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!