Python PIL 0.5 opacity, transparency, alpha

33,571

Solution 1

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(127)  # Half alpha; alpha argument must be an int
img.save(dest)

Solution 2

Could you do something like this?

from PIL import Image
image = Image.open('image.png') #open image
image = image.convert("RGBA")  #convert to RGBA
rgb = image.getpixel(x,y) #Get the rgba value at coordinates x,y
rgb[3] = int(rgb[3] / 2) or you could do rgb[3] = 50 maybe? #set alpha to half somehow
image.putpixel((x,y), rgb) #put back the modified reba values at same pixel coordinates

Definitely not the most efficient way of doing things but it might work. I wrote the code in browser so it might not be error free but hopefully it can give you an idea.

EDIT: Just noticed how old this question was. Leaving answer anyways for future help. :)

Solution 3

I put together Pecan's answer and cr333's question from this question:

Using PIL to make all white pixels transparent?

... and came up with this:

from PIL import Image

opacity_level = 170 # Opaque is 255, input between 0-255

img = Image.open('img1.png')
img = img.convert("RGBA")
datas = img.getdata()

newData = []
for item in datas:
    newData.append((0, 0, 0, opacity_level))
else:
    newData.append(item)

img.putdata(newData)
img.save("img2.png", "PNG")

In my case, I have text with black background and wanted only the background semi-transparent, in which case:

from PIL import Image

opacity_level = 170 # Opaque is 255, input between 0-255

img = Image.open('img1.png')
img = img.convert("RGBA")
datas = img.getdata()

newData = []
for item in datas:
    if item[0] == 0 and item[1] == 0 and item[2] == 0:
        newData.append((0, 0, 0, opacity_level))
    else:
        newData.append(item)

img.putdata(newData)
img.save("img2.png", "PNG")
Share:
33,571
Anderson
Author by

Anderson

Updated on July 09, 2022

Comments

  • Anderson
    Anderson almost 2 years

    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.