Search code examples
pythonpython-imaging-libraryalpha-transparency

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?


Solution

  • 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")