Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Image Library - Make area of image transparent

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?

like image 996
DizzyDoo Avatar asked Mar 07 '26 02:03

DizzyDoo


2 Answers

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")
like image 160
MatthieuW Avatar answered Mar 09 '26 17:03

MatthieuW


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.

like image 33
halex Avatar answered Mar 09 '26 17:03

halex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!