Definition
A Pillow submodule used for drawing 2D vector primitives (lines, shapes, and text) directly onto an existing Image object.
Why It Matters
It allows for the programmatic creation of graphics, from simple shapes to complex diagrams, directly within Python scripts. This capability is essential for automating the generation of reports, dynamic charts, and specialized visual assets in data-heavy workflows.
Core Concepts
from PIL import Image, ImageDraw
im = Image.new('RGBA', (200, 200), 'white')
draw = ImageDraw.Draw(im)
# Drawing shapes
draw.line([(0, 0), (199, 199)], fill='black', width=5)
draw.rectangle((20, 20, 60, 60), fill='red', outline='blue')
draw.ellipse((120, 30, 160, 70), fill='green')
im.show()
- The Draw Object: You cannot draw on an Image object directly. You must first create a separate
ImageDraw.Draw(im)object. - Vector Primitives:
line([coords], fill, width): Connects points.rectangle(box, fill, outline): Draws a box.ellipse(box, fill, outline): Draws a circle/oval within the box.polygon([coords], fill, outline): Custom shape.
- Text:
text((x, y), string, fill, font). Requires theImageFontmodule to load specific.ttffiles.