Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python PIL - check if image is transparent

I am pasting an image on another image, and after looking at this question, I saw that in order to paste a transparent image, you need to do

background = Image.open("test1.png")
foreground = Image.open("test2.png")

background.paste(foreground, (0, 0), foreground)

with a normal image, you should do

background = Image.open("test1.png")
foreground = Image.open("test2.png")

background.paste(foreground, (0, 0)) // difference here

my question is, how can I check if an image it transparent so I can determine how to use the paste method (with or without the last parameter).

like image 978
Ofek Agmon Avatar asked May 09 '17 07:05

Ofek Agmon


1 Answers

I've come up with the following function as a no-dependencies solution (besides PIL of course), which takes a PIL Image object as an argument:

def has_transparency(img):
    if image.info.get("transparency", None) is not None:
        return True
    if img.mode == "P":
        transparent = img.info.get("transparency", -1)
        for _, index in img.getcolors():
            if index == transparent:
                return True
    elif img.mode == "RGBA":
        extrema = img.getextrema()
        if extrema[3][0] < 255:
            return True

    return False

This function works by first checking to see if a "transparency" property is defined in the image's info -- if so, we return "True". Then, if the image is using indexed colors (such as in GIFs), it gets the index of the transparent color in the palette (img.info.get("transparency", -1)) and checks if it's used anywhere in the canvas (img.getcolors()). If the image is in RGBA mode, then presumably it has transparency in it, but it double-checks by getting the minimum and maximum values of every color channel (img.getextrema()), and checks if the alpha channel's smallest value falls below 255.

like image 140
Vinyl Da.i'gyu-Kazotetsu Avatar answered Oct 20 '22 12:10

Vinyl Da.i'gyu-Kazotetsu