Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing semi-transparent polygons in PIL

How do you draw semi-transparent polygons using the Python Imaging Library?

like image 407
adinsa Avatar asked Jun 25 '10 17:06

adinsa


2 Answers

Can you draw the polygon on a separate RGBA image then use the Image.paste(image, box, mask) method?

Edit: This works.

from PIL import Image
from PIL import ImageDraw
back = Image.new('RGBA', (512,512), (255,0,0,0))
poly = Image.new('RGBA', (512,512))
pdraw = ImageDraw.Draw(poly)
pdraw.polygon([(128,128),(384,384),(128,384),(384,128)],
              fill=(255,255,255,127),outline=(255,255,255,255))
back.paste(poly,mask=poly)
back.show()

http://effbot.org/imagingbook/image.htm#image-paste-method

like image 152
Nick T Avatar answered Oct 05 '22 16:10

Nick T


Using the Image.paste(image, box, mask) method will convert the alpha channel in the pasted area of the background image into the corresponding transparency value of the polygon image.

The Image.alpha_composite(im1,im2) method utilizes the alpha channel of the "pasted" image, and will not turn the background transparent. However, this method again needs two equally sized images.

like image 30
uwezi Avatar answered Oct 05 '22 17:10

uwezi