Python PIL Tkinter image transparency.

Beat_Slayer

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!

1,036 Views
About the Author
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()
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 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.