Search on blog:

How to draw triangel, rectangle or polygon with border and filling color using PIL/Pillow in Python

It is example how to use module PIL or Pillow to draw polygon with border and/or with filling color.

Example 1

This code creates triangle in the corners of empty image.

from PIL import Image, ImageDraw

# create empty image
img = Image.new('RGB', (100,100))

# create object which let you draw on this image
drw = ImageDraw.Draw(img)

# polygon with filling color and with default white border
drw.polygon([95,5,80,5,95,20])

# polygon without filling color and with red border
drw.polygon([5,95,5,80,20,95], outline=(255,0,0))

# polygon with green filling color and without border
drw.polygon([5,5,5,20,20,5], fill=(0,255,0))

# polygon with green filling color and with red border
drw.polygon([95,95,95,80,80,95], fill=(0,255,0), outline=(255,0,0))

# save to file
img.save('result.png')
pillow drawing polygons

Example 2

from PIL import Image, ImageDraw, ImageOps

# load image from file
img = Image.open('trzmiel.png')

# resize image by adding white border
img_with_border = ImageOps.expand(img, border=5, fill='white')

# create objec which let you draw on this image
drw = ImageDraw.Draw(img_with_border)

# width, height
w, h = img_with_border.size

# polygon sizes - size 1, size 2
s1 = 25
s2 = 50

# polygon with white filling color and without border
drw.polygon([s1,0,s2,0,0,s2,0,s1], fill=(200,200,200))
drw.polygon([w-s1,0,w-s2,0,w,s2,w,s1], fill=(200,200,200))
drw.polygon([w-s1,h,w-s2,h,w,h-s2,w,h-s1], fill=(200,200,200))
drw.polygon([s1,h,s2,h,0,h-s2,0,h-s1], fill=(200,200,200))

# save to file
img_with_border.save('result.png')
pillow drawing polygons pillow drawing polygons
If you like it
Buy a Coffee