Reputation: 2681
I'm trying to make the black pixels in the background of an image transparent. For this, I wrote the function below. I then overlay the image (a car in the center surrounded by black pixels) on a copy of itself and move the first one slowly. I was expecting the first image to reveal the copy underneath without showing the rectangular boundary since that part should have been transparent. However, I don't get the desired effect. Does anyone know what I'm missing?
def makeImageTransparent(img):
img = img.convert("RGBA")
datas = img.getdata()
newData = []
ii = 0
for item in datas:
if item[0] == 0 and item[1] == 0 and item[2] == 0:
newData.append((0, 0, 0, 0))
ii = ii + 1
else:
newData.append(item)
print str(ii)
img.putdata(newData)
return img
Upvotes: 1
Views: 187
Reputation: 2681
I couldn't figure out how to make the transparency work, so I just created my own paste method that updated the bytes of the image I was pasting to directly and this got me the desired effect.
def pasteImage(img, bigim, posn):
pixdata = img.load()
width, height = img.size
mainpixdata = bigim.load()
for y in xrange(height):
for x in xrange(width):
if pixdata[x, y] != (0, 0, 0, 0):
mainpixdata[x+posn[0], y+posn[1]] = pixdata[x,y]
Upvotes: 1