Python PIL 0.5 opacity, transparency, alpha

Anderson picture Anderson · Jul 14, 2014 · Viewed 26k times · Source

Is there any way to make an image half transparent?

the pseudo code is something like this:

from PIL import Image
image = Image.open('image.png')
image = alpha(image, 0.5)

I googled it for a couple of hours but I can't find anything useful.

Answer

Clayton Geist picture Clayton Geist · Jul 16, 2017

I realize this question is really old, but with the current version of Pillow (v4.2.1), there is a function called putalpha. It seems to work fine for me. I don't know if will work for every situation where you need to change the alpha, but it does work. It sets the alpha value for every pixel in the image. It seems, though that you can use a mask: http://www.leancrew.com/all-this/2013/11/transparency-with-pil/.

Use putalpha like this:

from PIL import Image
img = Image.open(image)
img.putalpha(128)  # Half alpha; alpha argument must be an int
img.save(dest)