Python Image Library - Make area of image transparent
Asked Answered
I

2

3

I have a quick question for someone who knows the Python Image Library better than I do. I have a png image with an alpha-channel, and I want the top two rows of pixels to be completely transparent. That's it! So far, my efforts make the top two rows transparent, but the original image loses it's alpha-channel information. Anyone know the best way to achieve this?

Impresario answered 1/9, 2012 at 15:1 Comment(0)
S
4

You can do this way.

img = Image.open("withAlpha.png")
p = img.load()

for y in range(2):
    for x in range(img.size[0]):
        t = list(p[x,y])
        t[3] = 0
        p[x,y] = tuple(t)

img.save("result.png")
Staurolite answered 1/9, 2012 at 15:54 Comment(0)
L
3

I would do it the following way:

img = Image.open("myimage.png")
p = img.load()
alpha = img.split()[-1]
width, height = img.size
for y in range(2): #First two rows
    for x in range(width): #The whole row
        alpha[x, y] = 0
img.putalpha(alpha)

I hope this works.

Lewendal answered 1/9, 2012 at 15:38 Comment(2)
It looks like it should work! But there's an issue when I do img.split(): File "C:\Python27\lib\site-packages\PIL\Image.py", line 1497, in split if self.im.bands == 1: AttributeError: 'NoneType' object has no attribute 'bands'. The image is definitely loaded correctly (it isn't none). What might be going on here?Impresario
I think you have to add a call to img.load because Image.open is lazy :).Lewendal

© 2022 - 2024 — McMap. All rights reserved.