Python枕头:向图像添加透明渐变 [英] Python Pillow: Add transparent gradient to an image

查看:480
本文介绍了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')

这篇关于Python枕头:向图像添加透明渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆