Search code examples
pythonimagepython-imaging-librarytransparencyimage-conversion

Check if an image is transparent or not


I'm trying to check an image is transparent or not using PIL.

image = Image.open(file).convert('RGBA') 
alpha = image.split()[-1]

This gives a value like this

<PIL.Image.Image image mode=L size=714x303 at 0x25EB0EBC040>

How to convert this to a transparency value? Or is this a right way to find the transparency of an image by converting it to RGBA?


Solution

  • image.getextrema() gives the min/max ranges for each channel, so you could use that to check the range on the alpha channel:

    image = Image.open(file).convert('RGBA') 
    alpha_range = image.getextrema()[-1]
    
    if alpha_range == (255,255):
        print("image is not transparent")
    

    Edit: did a quick search. You could also add some checks on the image mode, see the answers here too python PIL - check if image is transparent