DEV Community

Cover image for Using Pillow module to draw figures with Python
Onelinerhub
Onelinerhub

Posted on

Using Pillow module to draw figures with Python

1. How to draw a line

from PIL import Image, ImageDraw

im = Image.new("RGB", (400, 300))  
dr = ImageDraw.Draw(im)
dr.line([(50,200), (350,200)], fill ="white", width = 5)
im.show()
Enter fullscreen mode Exit fullscreen mode
  • ImageDraw.Draw - create drawing object,
  • .line( - draws a line,
  • (50,200), (350,200) - starting and ending coordinates of a line.

Open original or edit on Github.

2. How to draw a point

from PIL import Image, ImageDraw

im = Image.new("RGB", (400, 300))  
dr = ImageDraw.Draw(im)
dr.point((50,50), fill="white")
im.show()
Enter fullscreen mode Exit fullscreen mode
  • .point( - draws a single point,
  • (50,50) - point coordinates.

Open original or edit on Github.

3. How to draw a triangle

from PIL import Image, ImageDraw

im = Image.new("RGB", (400, 300))  
dr = ImageDraw.Draw(im)
dr.polygon([(50,50), (350,150), (200, 250)], outline="white")
im.show()
Enter fullscreen mode Exit fullscreen mode
  • .polygon( - draws polygon from given coordinates (with any number of dots),
  • (50,50), (350,150), (200, 250) - triangle dots coordinates.

Open original or edit on Github.

4. How to draw an arc

from PIL import Image, ImageDraw

im = Image.new("RGB", (400, 300))  
dr = ImageDraw.Draw(im)
dr.arc([(50,50), (350,250)], start = 20, end = 230, fill ="white")
im.show()
Enter fullscreen mode Exit fullscreen mode
  • .arc( - draws an arc,
  • (50,50), (350,250) - coordinates of an arc bounding rectangle,
  • start = 20 - starting angle (starts from 3pm),
  • end = 230 - ending angle.

Open original or edit on Github.

5. How to draw an ellipse

from PIL import Image, ImageDraw

im = Image.new("RGB", (400, 300))  
dr = ImageDraw.Draw(im)
dr.ellipse([(50,50), (350,250)], outline ="white")
im.show()
Enter fullscreen mode Exit fullscreen mode
  • .ellipse( - draws an ellipse,
  • (50,50), (350,250) - bounding rectangle to fit ellipse into.

Open original or edit on Github.

6. How to draw rectangle

from PIL import Image, ImageDraw

im = Image.new("RGB", (400, 300))  
dr = ImageDraw.Draw(im)
dr.rectangle([(50,50), (350,250)], outline="white")
im.show()
Enter fullscreen mode Exit fullscreen mode
  • .rectangle( - draws rectangle,
  • (50,50), (350,250) - rectangle top left and bottom right points coordinates.

Open original or edit on Github.

Top comments (0)