Pandora
Pandora

Reputation: 61

Python PIL reduce alpha level, but do not change transparent background

I want to make the visible part of image more transparent, but also do not change the alpha-level of fully-transparent background.

Here's the image: enter image description here

and I do it like this:

from PIL import Image
img = Image.open('image_with_transparent_background.png')
img.putalpha(128)
img.save('half_transparent_image_with_preserved_background.png')

And here is what I get: half_transparent_image_with_preserved_background.png

How do I achieve exactly what I want - so, without changing the background?

Upvotes: 4

Views: 2384

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207465

I think you want to make the alpha 128 anywhere it is currently non-zero:

from PIL import Image

# Load image and extract alpha channel
im = Image.open('moth.png')
A = im.getchannel('A')

# Make all opaque pixels into semi-opaque
newA = A.point(lambda i: 128 if i>0 else 0)

# Put new alpha channel back into original image and save
im.putalpha(newA)
im.save('result.png')

enter image description here


If you are happier doing that with Numpy, you can do:

from PIL import Image
import numpy as np

# Load image and make into Numpy array
im = Image.open('moth.png')
na = np.array(im)

# Make alpha 128 anywhere is is non-zero
na[...,3] = 128 * (na[...,3] > 0)

# Convert back to PIL Image and save
Image.fromarray(na).save('result.png')

Upvotes: 6

Related Questions