Python Pillow: Add transparent gradient to an image
<p>I need to add transparent gradient to an image like on the image below , I tried this:</p>

<pre><code>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')
</code></pre>

<p>But with this I added only white gradient. How can I change color of gradient and control size of gradient.</p>

<p>I need like the following but without text.</p>

<p><a href="http://i.stack.imgur.com/4TECp.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/4TECp.jpg" alt="this"></a></p>

<p>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.</p>

<pre><code>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')
</code></pre>

<h1>EDIT</h1>

<p>There are different ways to scale the gradient. Below is one suggestion.</p>

<pre><code>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')
</code></pre>

python python-imaging-library pillow