14

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)
...
martineau
  • 119,623
  • 25
  • 170
  • 301
Hoff
  • 38,776
  • 17
  • 74
  • 99

2 Answers2

34
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.

martineau
  • 119,623
  • 25
  • 170
  • 301
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
4

No source code, but this is the general approach that should work: Create an alpha channel for the image in "L" (grayscale) mode as a separate image object. Fill the alpha channel with white (full opacity) and draw the rectangle on the alpha channel image in black (full transparency). Convert the image to which you want to apply the transparency to RGBA and use the image object putalpha() method to copy the alpha channel you created into the image's alpha channel. Save as PNG.

kindall
  • 178,883
  • 35
  • 278
  • 309