Python: invert image with transparent background (PIL, Gimp,...)

gimp, python, python-imaging-library, transparency

Solution

`ImageChops.invert` seems to also invert the alpha channel of each pixel.

This should do the job:

import Image

img = Image.open('image.png').convert('RGBA')

r, g, b, a = img.split()

def invert(image):
    return image.point(lambda p: 255 - p)

r, g, b = map(invert, (r, g, b))

img2 = Image.merge(img.mode, (r, g, b, a))

img2.save('image2.png')

Problem

I have a set of white icons on transparent background, and I'd like to invert them all to be black on transparent background. Have tried with PIL (ImageChops) but it does not seem to work with transparent backgrounds. I've also tried Gimp's Python interface, but no luck there, either. Any idea how inverting is best achieved in Python?

Original source