Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
...
like image 818
Hoff Avatar asked Dec 07 '10 18:12

Hoff


People also ask

Does PNG allow partial transparency?

PNG images can contain alpha (transparency) information. Unlike GIF, which requires a particular color to be designated fully transparent, PNG allows the transparency of all pixels to take any value from fully transparent though partial transparency to full opacity.

Can PNG handle transparency?

The GIF and PNG formats also both support transparency. If you need any level of transparency in your image, you must use either a GIF or a PNG. GIF images (and also PNG) support 1-color transparency. This basically means that you can save your image with a transparent background.


1 Answers

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.

like image 75
unutbu Avatar answered Sep 30 '22 01:09

unutbu