Reputation: 2607
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.
Upvotes: 1
Views: 2421
Reputation: 117313
Given what you are "pasting" is just a uniform (transparent) color value, you don't need to create a separate image for the rectangle you're pasting, you can just pass a single color value to paste()
.
from PIL import Image
color = (255, 255, 255, 0)
paste_pos = (200, 400, 100, 300)
im = Image.open("your-image.jpg").convert("RGBA")
im.paste(color, paste_pos)
im.show()
Upvotes: 0
Reputation: 1489
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()
Upvotes: 3