project.py
project.py

Reputation: 103

How to create different transparency like gradient with python pil?

Can I do something like this with python pillow? Don't know how to describe it.

enter image description here

Upvotes: 0

Views: 1535

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207465

Updated Answer

This is easier than my original answer:

#!/usr/bin/env python3

from PIL import Image

# Define width and height
w, h = 400, 200

# Make solid orange background
im = Image.new('RGB', (w,h), 'orange')

# Build an alpha/transparency channel
alpha = Image.linear_gradient('L').rotate(-90).resize((w,h))
alpha.save('DEBUG-alpha.png')

# Put our lovely new alpha channel into orange image
im.putalpha(alpha)
im.save('result.png')

enter image description here

Here is how the alpha channel looks - I have added a red border so you can see its extent on any background:

enter image description here

If you want to change the roll-off rate between orange and transparency, you can do this:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Define width and height
w, h = 400, 200

# Make solid orange background
im = Image.new('RGB', (w,h), 'orange')

# Build an alpha/transparency channel
alpha = Image.linear_gradient('L').rotate(-90).resize((w,h))

# Optional gamma adjustment. Smaller gamma makes image darker, bigger gamma makes it brighter
gamma = 0.4
alpha = alpha.point(lambda f: int((f/255.0)**(1/gamma)*255))
alpha.save('DEBUG-alpha.png')

# Put our lovely new alpha channel into orange image
im.putalpha(alpha)
im.save('result.png')

enter image description here enter image description here

Original Answer

You can do it like this:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Define width and height
w, h = 400, 200

# Make solid orange background
im = Image.new('RGB', (w,h), 'orange')

# Build an alpha/transparency channel
# ... make one line w pixels wide, going from 255..0
line = np.linspace(255,0, num=w, dtype=np.uint8)
# ... repeat that line h times to get the full height of the image
alpha = np.tile(line, (h,1))

# Put our lovely new alpha channel into orange image
im.putalpha(Image.fromarray(alpha))

im.save('result.png')

Upvotes: 1

Related Questions