tags:

views:

1390

answers:

4

I'm trying to make all white pixels transparent using the Python Image Library. (I'm a C hacker trying to learn python so be gentle) I've got the conversion working (at least the pixel values look correct) but I can't figure out how to convert the list into a buffer to re-create the image. Here's the code

img = Image.open('img.png')
imga = img.convert("RGBA")
datas = imga.getdata()

newData = list()
for item in datas:
    if item[0] == 255 and item[1] == 255 and item[2] == 255:
        newData.append([255, 255, 255, 0])
    else:
        newData.append(item)

imgb = Image.frombuffer("RGBA", imga.size, newData, "raw", "RGBA", 0, 1)
imgb.save("img2.png", "PNG")
+5  A: 

You need to make the following changes:

  • append a tuple (255, 255, 255, 0) and not a list [255, 255, 255, 0]
  • use img.putdata(newData)

This is the working code:

from PIL import Image

img = Image.open('img.png')
img = img.convert("RGBA")
datas = imga.getdata()
newData = list()

for item in datas:
  if item[0] == 255 and item[1] == 255 and item[2] == 255:
    newData.append((255, 255, 255, 0))
  else:
    newData.append(item)

img.putdata(newData)
img.save("img2.png", "PNG")
cr333
+6  A: 

You can also use pixel access mode to modify the image in-place:

from PIL import Image

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

pixdata = img.load()

for y in xrange(img.size[1]):
    for x in xrange(img.size[0]):
        if pixdata[x, y] == (255, 255, 255, 255):
            pixdata[x, y] = (255, 255, 255, 0)

img.save("img2.png", "PNG")
keithb
isn't tuple a mutable type?
DataGreed
it works! Not long enough? Well it really works!
Fabien
+1  A: 

Here is a mailing list message that seems appropriate. The solution is much more complicated than those presented here, but possibly faster.

Rick Copeland
The message deals with applying an affine transform to an image, which is not at all the same as replacing pixels of a given color by another.
Fabien
+1  A: 

Or if you'd just like to download pre-computed white/black pixels, grab this .zip: http://transparentpixelpack.prestonlee.com

Preston Lee