0
votes

you might know the "Color to transparency" effect of professional image editing programs like Photoshop. How is this effect done? I want to add some transparency to my images programmatically with Python (and for testing PIL, because I can check with generated images). This effect is going to be used for some fractal things, so here's my current code:

i = "i.png"
o = "o.png"

key = (0, 0, 0, 255)

from PIL import Image as I

_i = I.open(i)
_ii = _i.load()

_o = I.new("RGBA", _i.size)
_oo = _o.load()

for x in range(0, _i.size[0]): 
    for y in range(0, _i.size[1]): 
        col = list(_ii[x, y])
        for i in range(0, 4): 
            col[i] = abs(col[i] - key[i])
        _oo[x, y] = tuple(col)

_o.save(o)

I thought of subtracting the both colors, but i end up with black images (loses all alpha). Another thought was to double the original color and check if the key is lower, like reverse-mixing the two colors.

So, do you have any ideas?

EDIT

Example of "Color to transparency"

This effect was done with GIMP using it's "Color to transparency" function. I selected #FFF to be transparent and GIMP somehow made white to transparent, without ignoring the color of the pixel at first. This is, what I actually want to do, make a color in an image transparent, like in the image.

(I added a black background to the second image, so you know it's transparent. The original image was just like the first one, white background, slightly green surrounding, black center)

1
Check out this wikipedia article: en.wikipedia.org/wiki/… - fodma1
I read this article several times but I actually don't get it. Might be, because I'm pretty tired after coding night... Could you help me along this? - michaeln

1 Answers

0
votes

If you want to replace the pixel of a given color by "transparent" pixels, you have (1) to test if a given pixel has the required color (2) set it "transparent" by setting alpha to 0. Something like that would do the trick:

for x in range(0, _i.size[0]): 
    for y in range(0, _i.size[1]): 
        col = list(_ii[x, y])
        if col[0:3] == my_key_color[0:3]:
            _oo[x,y] = col[0:3]+(0,) # keep RGB, set A to 0
        else:
            _oo[x,y] = col

Please note this is a very basic solution where a pixel is either fully transparent -- or leaved as-is. If you looking for more "professional" effect, you will have te refine this a little...