Search code examples
python-3.xpython-imaging-library

Erasing a rectangular area of PIL image


How can I erase and make transparent a rectangular area of a PIL image, without changing dimensions?

I implemented this by cropping the image & pasting on an empty image, but it cannot erase an area inside the image. My implementation is mostly just arithmetic, so I am trying to find a more elegant way of doing this.


Solution

  • You need to open it in RGBA mode.

    from PIL import Image
    
    rect_size = (100, 300)
    rect_pos = (200, 400)
    
    im = Image.open("your-image.jpg").convert("RGBA")
    rect = Image.new("RGBA", rect_size, (255, 255, 255, 0))
    im.paste(rect, rect_pos)
    im.show()