Python PIL Tkinter image transparency.

Beat_Slayer 0 Tallied Votes 2K Views Share

Simple script for image transparency.

Someone asked one some time ago, and i had other but for a different system, and decided to write a Python/PIL version.

The value of the color used as transparent is the value of the pixel at position (0, 0).

You can adjust tolerance value.

Happy coding!

import Tkinter 
import Image
import ImageTk

def color_cmp(orig, comp):
    tolerance = 5   #  You can adjust color tolerance value
    inside = []
    for i in range(len(orig) - 1):
        if (orig[i] - tolerance) <= comp[i] >= (orig[i] + tolerance):
            inside.append(True)
        else:
            inside.append(False)
    if not inside.count(False):
        return 255
    else:
        return 0

def automask(img):
    backcolor = img.getpixel((0, 0))
    alpha_mask = Image.new('1', img.size)
    alpha_mask.load()
    for y in range(img.size[1]):
        for x in range(img.size[0]):
            pix_color = img.getpixel((x, y))
            if color_cmp(pix_color, backcolor):
                alpha_mask.putpixel((x, y), 1)
            else:
                alpha_mask.putpixel((x, y), 0)
    img.putalpha(alpha_mask)
    return img

root = Tkinter.Tk()

masked = automask(Image.open('grim_reaper.jpg'))

maskedtk = ImageTk.PhotoImage(masked)

Tkinter.Label(root, image=maskedtk).pack()

root.mainloop()

Dani AI

Generated

Short clarification and a reliable workaround.

's automask makes a proper RGBA image, but stacking a Label with transparent pixels on top of a Button won't reveal the button underneath — Tk/Tkinter does not do per-pixel alpha compositing between separate widgets. Window-level attributes like -alpha or -transparentcolor affect the whole toplevel and are platform-dependent, so they won't make a Label show the Button beneath. (stackoverflow.com)

Recommended fix: do the compositing in PIL and hand Tk a single final image. Open both images as RGBA, paste the foreground into a same-size transparent layer using the foreground itself as mask, then alpha_composite that layer onto the background. Convert the result to an ImageTk.PhotoImage and apply it to the Button/Label. Pillow’s ImageTk treats fully transparent pixels specially, and for correct blending you should pre-compose in PIL. Example workflow:

from PIL import Image, ImageTk

bg = Image.open("button.png").convert("RGBA")
fg = Image.open("overlay.png").convert("RGBA")
layer = Image.new("RGBA", bg.size)
layer.paste(fg, (x, y), fg)             # use fg's alpha as mask
out = Image.alpha_composite(bg, layer)
tk = ImageTk.PhotoImage(out)
button.config(image=tk)
button.image = tk   # keep a reference so Python doesn't GC the image

This matches what hinted at but preserves partial alpha and avoids creating awkward widget stacking. If you prefer drawing at runtime, put both images on a single Canvas with create_image, but still pre-compose in PIL when you need true alpha blending. Also remember to keep a Python reference to the PhotoImage to prevent it disappearing. (hugovk-pillow.readthedocs.io)

gleam.uahmed 3 Newbie Poster

Hi , But it doesnt work perfect when i want to putt that image over a button having image ! , it doesnt show any transparency

richieking 44 Master Poster

Simple transparent overlaying image

import Image

handle = Image.open("fd.png")## Your first image file name

handle.putalpha(30)
handle.save("bv.png")
df=Image.open("bv.png")
dd =Image.open("i.jpg") ## Put your second image file name here
df.paste(dd,(100,200))
df.save("gg.png")

This is more simple :)

gleam.uahmed 3 Newbie Poster

Offcourse it is but it will create a new picture and still the transperency issue remain when u putt a label with transparent pic over the button it will not work ..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.