The :py~PIL.ImageDraw
module provides simple 2D graphics for :py~PIL.Image.Image
objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.
For a more advanced drawing library for PIL, see the aggdraw module.
import sys
from PIL import Image, ImageDraw
with Image.open("hopper.jpg") as im:
draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)
# write to stdout
im.save(sys.stdout, "PNG")
The graphics interface uses the same coordinate system as PIL itself, with (0, 0) in the upper left corner. Any pixels drawn outside of the image bounds will be discarded.
To specify colors, you can use numbers or tuples just as you would use with :pyPIL.Image.new
or :pyPIL.Image.Image.putpixel
. For “1”, “L”, and “I” images, use integers. For “RGB” images, use a 3-tuple containing integer values. For “F” images, use integer or floating point values.
For palette images (mode “P”), use integers as color indexes. In 1.1.4 and later, you can also use RGB 3-tuples or color names (see below). The drawing layer will automatically assign color indexes, as long as you don’t draw with more than 256 colors.
See color-names
for the color names supported by Pillow.
PIL can use bitmap fonts or OpenType/TrueType fonts.
Bitmap fonts are stored in PIL's own format, where each font typically consists of two files, one named .pil and the other usually named .pbm. The former contains font metrics, the latter raster data.
To load a bitmap font, use the load functions in the :py~PIL.ImageFont
module.
To load a OpenType/TrueType font, use the truetype function in the :py~PIL.ImageFont
module. Note that this function depends on third-party libraries, and may not available in all PIL builds.
from PIL import Image, ImageDraw, ImageFont
# get an image
with Image.open("Pillow/Tests/images/hopper.png").convert("RGBA") as base:
# make a blank image for the text, initialized to transparent text color
txt = Image.new("RGBA", base.size, (255, 255, 255, 0))
# get a font
fnt = ImageFont.truetype("Pillow/Tests/fonts/FreeMono.ttf", 40)
# get a drawing context
d = ImageDraw.Draw(txt)
# draw text, half opacity
d.text((10, 10), "Hello", font=fnt, fill=(255, 255, 255, 128))
# draw text, full opacity
d.text((10, 60), "World", font=fnt, fill=(255, 255, 255, 255))
out = Image.alpha_composite(base, txt)
out.show()
from PIL import Image, ImageDraw, ImageFont
# create an image
out = Image.new("RGB", (150, 100), (255, 255, 255))
# get a font
fnt = ImageFont.truetype("Pillow/Tests/fonts/FreeMono.ttf", 40)
# get a drawing context
d = ImageDraw.Draw(out)
# draw multiline text
d.multiline_text((10, 10), "Hello\nWorld", font=fnt, fill=(0, 0, 0))
out.show()