Search code examples
pythonimagepngtransparencypython-imaging-library

PIL: How to make area transparent in PNG?


I've been using PIL to crop Images, now I also want to make certain rectangular areas transparent, say

from PIL import Image
im = Image.open("sample.png")
transparent_area = (50,80,100,200)
...

Solution

  • from PIL import Image
    from PIL import ImageDraw
    im = Image.open("image.png")
    transparent_area = (50,80,100,200)
    
    mask=Image.new('L', im.size, color=255)
    draw=ImageDraw.Draw(mask) 
    draw.rectangle(transparent_area, fill=0)
    im.putalpha(mask)
    im.save('/tmp/output.png')
    

    I learned how to do this here.