

Image moduleImageChops (“channel operations”) moduleImageCms moduleImageColor moduleImageDraw moduleImageEnhance moduleImageFile moduleImageFilter moduleImageFont moduleImageGrab moduleImageMath moduleImageMorph moduleImageOps moduleImagePalette moduleImagePath moduleImageQt moduleImageSequence moduleImageShow moduleImageStat moduleImageText moduleImageTk moduleImageTransform moduleImageWin module (Windows-only)ExifTags moduleTiffTags moduleJpegPresets modulePSDraw modulePixelAccess classfeatures moduleImageDraw module¶TheImageDraw module provides simple 2D graphics forImage objects. You can use this module to create newimages, annotate or retouch existing images, and to generate graphics on thefly for web use.
For a more advanced drawing library for PIL, see theaggdraw module.
importsysfromPILimportImage,ImageDrawwithImage.open("hopper.jpg")asim: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 stdoutim.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 willbe discarded.
To specify colors, you can use numbers or tuples just as you would use withPIL.Image.new(). SeeColors for more information.
For palette images (mode “P”), use integers as color indexes. In 1.1.4 andlater, you can also use RGB 3-tuples or color names (see below). The drawinglayer will automatically assign color indexes, as long as you don’t draw withmore than 256 colors.
SeeColor names for the color names supported by Pillow.
By default, when drawing onto an existing image, the image’s pixel values are simplyreplaced by the new color:
im=Image.new("RGBA",(1,1),(255,0,0))d=ImageDraw.Draw(im)d.rectangle((0,0,1,1),(0,255,0,127))assertim.getpixel((0,0))==(0,255,0,127)# Alpha channel values have no effect when drawing with RGB modeim=Image.new("RGB",(1,1),(255,0,0))d=ImageDraw.Draw(im)d.rectangle((0,0,1,1),(0,255,0,127))assertim.getpixel((0,0))==(0,255,0)
If you would like to combine translucent color with an RGB image, then initialize theImageDraw instance with the RGBA mode:
fromPILimportImage,ImageDrawim=Image.new("RGB",(1,1),(255,0,0))d=ImageDraw.Draw(im,"RGBA")d.rectangle((0,0,1,1),(0,255,0,127))assertim.getpixel((0,0))==(128,127,0)
If you would like to combine translucent color with an RGBA image underneath, you willneed to combine multiple images:
fromPILimportImage,ImageDrawim=Image.new("RGBA",(1,1),(255,0,0,255))im2=Image.new("RGBA",(1,1))d=ImageDraw.Draw(im2)d.rectangle((0,0,1,1),(0,255,0,127))im.paste(im2.convert("RGB"),mask=im2)assertim.getpixel((0,0))==(128,127,0,255)
PIL can use bitmap fonts or OpenType/TrueType fonts.
Bitmap fonts are stored in PIL’s own format, where each font typically consistsof two files, one named .pil and the other usually named .pbm. The formercontains font metrics, the latter raster data.
To load a bitmap font, use the load functions in theImageFontmodule.
To load a OpenType/TrueType font, use the truetype function in theImageFont module. Note that this function depends on third-partylibraries, and may not available in all PIL builds.
fromPILimportImage,ImageDraw,ImageFont# get an imagewithImage.open("Pillow/Tests/images/hopper.png").convert("RGBA")asbase:# make a blank image for the text, initialized to transparent text colortxt=Image.new("RGBA",base.size,(255,255,255,0))# get a fontfnt=ImageFont.truetype("Pillow/Tests/fonts/FreeMono.ttf",40)# get a drawing contextd=ImageDraw.Draw(txt)# draw text, half opacityd.text((10,10),"Hello",font=fnt,fill=(255,255,255,128))# draw text, full opacityd.text((10,60),"World",font=fnt,fill=(255,255,255,255))out=Image.alpha_composite(base,txt)out.show()
fromPILimportImage,ImageDraw,ImageFont# create an imageout=Image.new("RGB",(150,100),(255,255,255))# get a fontfnt=ImageFont.truetype("Pillow/Tests/fonts/FreeMono.ttf",40)# get a drawing contextd=ImageDraw.Draw(out)# draw multiline textd.multiline_text((10,10),"Hello\nWorld",font=fnt,fill=(0,0,0))out.show()
Creates an object that can be used to draw in the given image.
Note that the image will be modified in place.
im – The image to draw in.
mode – Optional mode to use for color values. For RGBimages, this argument can be RGB or RGBA (to blend thedrawing into the image). For all other modes, this argumentmust be the same as the image mode. If omitted, the modedefaults to the mode of the image.
Selects whetherImageDraw.ink should be used as a fill or outline color.
The current default font.
Can be set per instance:
fromPILimportImageDraw,ImageFontdraw=ImageDraw.Draw(image)draw.font=ImageFont.truetype("Tests/fonts/FreeMono.ttf")
Or globally for all future ImageDraw instances:
fromPILimportImageDraw,ImageFontImageDraw.ImageDraw.font=ImageFont.truetype("Tests/fonts/FreeMono.ttf")
The current font drawing mode.
Set to"1" to disable antialiasing or"L" to enable it.
Get the current default font,ImageDraw.font.
If the current default font isNone,it is initialized withImageFont.load_default().
An image font.
Draws an arc (a portion of a circle outline) between the start and endangles, inside the given bounding box.
xy – Two points to define the bounding box. Sequence of[(x0,y0),(x1,y1)] or[x0,y0,x1,y1], wherex1>=x0 andy1>=y0.
start – Starting angle, in degrees. Angles are measured from 3o’clock, increasing clockwise.
end – Ending angle, in degrees.
fill – Color to use for the arc.
width –
The line width, in pixels.
Added in version 5.3.0.
Draws a bitmap (mask) at the given position, using the current fill colorfor the non-zero portions. The bitmap should be a valid transparency mask(mode “1”) or matte (mode “L” or “RGBA”).
This is equivalent to doingimage.paste(xy,color,bitmap).
To paste pixel data into an image, use thepaste() method on the image itself.
Same asarc(), but connects the end pointswith a straight line.
xy – Two points to define the bounding box. Sequence of[(x0,y0),(x1,y1)] or[x0,y0,x1,y1], wherex1>=x0 andy1>=y0.
outline – Color to use for the outline.
fill – Color to use for the fill.
width –
The line width, in pixels.
Added in version 5.3.0.
Draws a circle with a given radius centering on a point.
Added in version 10.4.0.
xy – The point for the center of the circle, e.g.(x,y).
radius – Radius of the circle.
outline – Color to use for the outline.
fill – Color to use for the fill.
width – The line width, in pixels.
Draws an ellipse inside the given bounding box.
xy – Two points to define the bounding box. Sequence of either[(x0,y0),(x1,y1)] or[x0,y0,x1,y1], wherex1>=x0andy1>=y0.
outline – Color to use for the outline.
fill – Color to use for the fill.
width –
The line width, in pixels.
Added in version 5.3.0.
Draws a line between the coordinates in thexy list.The coordinate pixels are included in the drawn line.
xy – Sequence of either 2-tuples like[(x,y),(x,y),...] ornumeric values like[x,y,x,y,...].
fill – Color to use for the line.
width –
The line width, in pixels.
Added in version 1.1.5.
Note
This option was broken until version 1.1.6.
joint –
Joint type between a sequence of lines. It can be"curve", for rounded edges, orNone.
Added in version 5.3.0.
Same as arc, but also draws straight lines between the end points and thecenter of the bounding box.
xy – Two points to define the bounding box. Sequence of[(x0,y0),(x1,y1)] or[x0,y0,x1,y1], wherex1>=x0 andy1>=y0.
start – Starting angle, in degrees. Angles are measured from 3o’clock, increasing clockwise.
end – Ending angle, in degrees.
fill – Color to use for the fill.
outline – Color to use for the outline.
width –
The line width, in pixels.
Added in version 5.3.0.
Draws points (individual pixels) at the given coordinates.
xy – Sequence of either 2-tuples like[(x,y),(x,y),...] ornumeric values like[x,y,x,y,...].
fill – Color to use for the point.
Draws a polygon.
The polygon outline consists of straight lines between the givencoordinates, plus a straight line between the last and the firstcoordinate. The coordinate pixels are included in the drawn polygon.
xy – Sequence of either 2-tuples like[(x,y),(x,y),...] ornumeric values like[x,y,x,y,...].
fill – Color to use for the fill.
outline – Color to use for the outline.
width – The line width, in pixels.
Draws a regular polygon inscribed inbounding_circle,withn_sides, and rotation ofrotation degrees.
bounding_circle – The bounding circle is a tuple definedby a point and radius.(e.g.bounding_circle=(x,y,r) or((x,y),r)).The polygon is inscribed in this circle.
n_sides – Number of sides(e.g.n_sides=3 for a triangle,6 for a hexagon).
rotation – Apply an arbitrary rotation to the polygon(e.g.rotation=90, applies a 90 degree rotation).
fill – Color to use for the fill.
outline – Color to use for the outline.
width – The line width, in pixels.
Draws a rectangle.
xy – Two points to define the bounding box. Sequence of either[(x0,y0),(x1,y1)] or[x0,y0,x1,y1], wherex1>=x0 andy1>=y0. The bounding box is inclusive of both endpoints.
fill – Color to use for the fill.
outline – Color to use for the outline.
width –
The line width, in pixels.
Added in version 5.3.0.
Draws a rounded rectangle.
xy – Two points to define the bounding box. Sequence of either[(x0,y0),(x1,y1)] or[x0,y0,x1,y1], wherex1>=x0 andy1>=y0. The bounding box is inclusive of both endpoints.
radius – Radius of the corners.
fill – Color to use for the fill.
outline – Color to use for the outline.
width – The line width, in pixels.
corners – A tuple of whether to round each corner,(top_left,top_right,bottom_right,bottom_left).Keyword-only argument.
Added in version 8.2.0.
Warning
This method is experimental.
Draw a shape.
Draws the string at the given position.
xy – The anchor coordinates of the text.
text – String to be drawn. If it contains any newline characters,the text is passed on tomultiline_text().
fill – Color to use for the text.
font – AnImageFont instance.
anchor –
The text anchor alignment. Determines the relative location ofthe anchor to the text. The default alignment is top left,specificallyla for horizontal text andlt forvertical text. SeeText anchors for details.This parameter is ignored for non-TrueType fonts.
Note
This parameter was present in earlier versionsof Pillow, but implemented only in version 8.0.0.
spacing – If the text is passed on tomultiline_text(),the number of pixels between lines.
align –
If the text is passed on tomultiline_text(),"left","center","right" or"justify". Determinesthe relative alignment of lines. Use theanchor parameter tospecify the alignment toxy.
Added in version 11.2.1:"justify"
direction –
Direction of the text. It can be"rtl" (right toleft),"ltr" (left to right) or"ttb" (top to bottom).Requires libraqm.
Added in version 4.2.0.
features –
A list of OpenType font features to be used during textlayout. This is usually used to turn on optionalfont features that are not enabled by default,for example"dlig" or"ss01", but can be alsoused to turn off default font features, forexample"-liga" to disable ligatures or"-kern"to disable kerning. To get all supportedfeatures, seeOpenType docs.Requires libraqm.
Added in version 4.2.0.
language –
Language of the text. Different languages may usedifferent glyph shapes or ligatures. This parameter tellsthe font which language the text is in, and to apply thecorrect substitutions as appropriate, if available.It should be aBCP 47 language code.Requires libraqm.
Added in version 6.0.0.
stroke_width –
The width of the text stroke.
Added in version 6.2.0.
stroke_fill –
Color to use for the text stroke. If not given, will default tothefill parameter.
Added in version 6.2.0.
embedded_color –
Whether to use font embedded color glyphs (COLR, CBDT, SBIX).
Added in version 8.0.0.
font_size –
font is not provided, then the size to use for the defaultfont.Keyword-only argument.
Added in version 10.1.0.
Draws the string at the given position.
xy – The anchor coordinates of the text.
text – String to be drawn.
fill – Color to use for the text.
font – AnImageFont instance.
anchor –
The text anchor alignment. Determines the relative location ofthe anchor to the text. The default alignment is top left,specificallyla for horizontal text andlt forvertical text. SeeText anchors for details.This parameter is ignored for non-TrueType fonts.
Note
This parameter was present in earlier versionsof Pillow, but implemented only in version 8.0.0.
spacing – The number of pixels between lines.
align –
"left","center","right" or"justify". Determinesthe relative alignment of lines. Use theanchor parameter tospecify the alignment toxy.
Added in version 11.2.1:"justify"
direction –
Direction of the text. It can be"rtl" (right toleft),"ltr" (left to right) or"ttb" (top to bottom).Requires libraqm.
Added in version 4.2.0.
features –
A list of OpenType font features to be used during textlayout. This is usually used to turn on optionalfont features that are not enabled by default,for example"dlig" or"ss01", but can be alsoused to turn off default font features, forexample"-liga" to disable ligatures or"-kern"to disable kerning. To get all supportedfeatures, seeOpenType docs.Requires libraqm.
Added in version 4.2.0.
language –
Language of the text. Different languages may usedifferent glyph shapes or ligatures. This parameter tellsthe font which language the text is in, and to apply thecorrect substitutions as appropriate, if available.It should be aBCP 47 language code.Requires libraqm.
Added in version 6.0.0.
stroke_width –
The width of the text stroke.
Added in version 6.2.0.
stroke_fill –
thefill parameter.
Added in version 6.2.0.
embedded_color –
Whether to use font embedded color glyphs (COLR, CBDT, SBIX).
Added in version 8.0.0.
font_size –
font is not provided, then the size to use for the defaultfont.Keyword-only argument.
Added in version 10.1.0.
Returns length (in pixels with 1/64 precision) of given text when renderedin font with provided direction, features, and language.
This is the amount by which following text should be offset.Text bounding box may extend past the length in some fonts,e.g. when using italics or accents.
The result is returned as a float; it is a whole number if using basic layout.
Note that the sum of two lengths may not equal the length of a concatenatedstring due to kerning. If you need to adjust for kerning, include the followingcharacter and subtract its length.
For example, instead of
hello=draw.textlength("Hello",font)world=draw.textlength("World",font)hello_world=hello+world# not adjusted for kerningasserthello_world==draw.textlength("HelloWorld",font)# may fail
use
hello=draw.textlength("HelloW",font)-draw.textlength("W",font)# adjusted for kerningworld=draw.textlength("World",font)hello_world=hello+world# adjusted for kerningasserthello_world==draw.textlength("HelloWorld",font)# True
or disable kerning with (requires libraqm)
hello=draw.textlength("Hello",font,features=["-kern"])world=draw.textlength("World",font,features=["-kern"])hello_world=hello+world# kerning is disabled, no need to adjustasserthello_world==draw.textlength("HelloWorld",font,features=["-kern"])# True
See also
Added in version 8.0.0.
text – Text to be measured. May not contain any newline characters.
font – AnImageFont instance.
direction – Direction of the text. It can be"rtl" (right toleft),"ltr" (left to right) or"ttb" (top to bottom).Requires libraqm.
features – A list of OpenType font features to be used during textlayout. This is usually used to turn on optionalfont features that are not enabled by default,for example"dlig" or"ss01", but can be alsoused to turn off default font features, forexample"-liga" to disable ligatures or"-kern"to disable kerning. To get all supportedfeatures, seeOpenType docs.Requires libraqm.
language – Language of the text. Different languages may usedifferent glyph shapes or ligatures. This parameter tellsthe font which language the text is in, and to apply thecorrect substitutions as appropriate, if available.It should be aBCP 47 language code.Requires libraqm.
embedded_color – Whether to use font embedded color glyphs (COLR, CBDT, SBIX).
font_size –
font is not provided, then the size to use for the defaultfont.Keyword-only argument.
Added in version 10.1.0.
Either width for horizontal text, or height for vertical text.
Returns bounding box (in pixels) of given text relative to given anchorwhen rendered in font with provided direction, features, and language.Only supported for TrueType fonts.
Usetextlength() to get the offset of following text with1/64 pixel precision. The bounding box includes extra margins forsome fonts, e.g. italics or accents.
Added in version 8.0.0.
xy – The anchor coordinates of the text.
text – Text to be measured. If it contains any newline characters,the text is passed on tomultiline_textbbox().
font – AFreeTypeFont instance.
anchor – The text anchor alignment. Determines the relative location ofthe anchor to the text. The default alignment is top left,specificallyla for horizontal text andlt forvertical text. SeeText anchors for details.This parameter is ignored for non-TrueType fonts.
spacing – If the text is passed on tomultiline_textbbox(),the number of pixels between lines.
align –
If the text is passed on tomultiline_textbbox(),"left","center","right" or"justify". Determinesthe relative alignment of lines. Use theanchor parameter tospecify the alignment toxy.
Added in version 11.2.1:"justify"
direction – Direction of the text. It can be"rtl" (right toleft),"ltr" (left to right) or"ttb" (top to bottom).Requires libraqm.
features – A list of OpenType font features to be used during textlayout. This is usually used to turn on optionalfont features that are not enabled by default,for example"dlig" or"ss01", but can be alsoused to turn off default font features, forexample"-liga" to disable ligatures or"-kern"to disable kerning. To get all supportedfeatures, seeOpenType docs.Requires libraqm.
language – Language of the text. Different languages may usedifferent glyph shapes or ligatures. This parameter tellsthe font which language the text is in, and to apply thecorrect substitutions as appropriate, if available.It should be aBCP 47 language code.Requires libraqm.
stroke_width – The width of the text stroke.
embedded_color – Whether to use font embedded color glyphs (COLR, CBDT, SBIX).
font_size –
font is not provided, then the size to use for the defaultfont.Keyword-only argument.
Added in version 10.1.0.
(left,top,right,bottom) bounding box
Returns bounding box (in pixels) of given text relative to given anchorwhen rendered in font with provided direction, features, and language.Only supported for TrueType fonts.
Usetextlength() to get the offset of following text with1/64 pixel precision. The bounding box includes extra margins forsome fonts, e.g. italics or accents.
See also
Added in version 8.0.0.
xy – The anchor coordinates of the text.
text – Text to be measured.
font – AFreeTypeFont instance.
anchor – The text anchor alignment. Determines the relative location ofthe anchor to the text. The default alignment is top left,specificallyla for horizontal text andlt forvertical text. SeeText anchors for details.This parameter is ignored for non-TrueType fonts.
spacing – The number of pixels between lines.
align –
"left","center","right" or"justify". Determinesthe relative alignment of lines. Use theanchor parameter tospecify the alignment toxy.
Added in version 11.2.1:"justify"
direction – Direction of the text. It can be"rtl" (right toleft),"ltr" (left to right) or"ttb" (top to bottom).Requires libraqm.
features – A list of OpenType font features to be used during textlayout. This is usually used to turn on optionalfont features that are not enabled by default,for example"dlig" or"ss01", but can be alsoused to turn off default font features, forexample"-liga" to disable ligatures or"-kern"to disable kerning. To get all supportedfeatures, seeOpenType docs.Requires libraqm.
language – Language of the text. Different languages may usedifferent glyph shapes or ligatures. This parameter tellsthe font which language the text is in, and to apply thecorrect substitutions as appropriate, if available.It should be aBCP 47 language code.Requires libraqm.
stroke_width – The width of the text stroke.
embedded_color – Whether to use font embedded color glyphs (COLR, CBDT, SBIX).
font_size –
font is not provided, then the size to use for the defaultfont.Keyword-only argument.
Added in version 10.1.0.
(left,top,right,bottom) bounding box
Warning
This method is experimental.
A more advanced 2D drawing interface for PIL images,based on the WCK interface.
im – The image to draw in.
hints – An optional list of hints.
A (drawing context, drawing resource factory) tuple.
Warning
This method is experimental.
Fills a bounded region with a given color.
image – Target image.
xy – Seed position (a 2-item coordinate tuple). SeeCoordinate system.
value – Fill color.
border – Optional border value. If given, the region consists ofpixels with a color different from the border color. If not given,the region consists of pixels having the same color as the seedpixel.
thresh – Optional threshold value which specifies a maximumtolerable difference of a pixel value from the ‘background’ inorder for it to be replaced. Useful for filling regions ofnon-homogeneous, but similar, colors.
ImageDraw moduleImageDraw.getfont()ImageDraw.arc()ImageDraw.bitmap()ImageDraw.chord()ImageDraw.circle()ImageDraw.ellipse()ImageDraw.line()ImageDraw.pieslice()ImageDraw.point()ImageDraw.polygon()ImageDraw.regular_polygon()ImageDraw.rectangle()ImageDraw.rounded_rectangle()ImageDraw.shape()ImageDraw.text()ImageDraw.multiline_text()ImageDraw.textlength()ImageDraw.textbbox()ImageDraw.multiline_textbbox()getdraw()floodfill()