ImageDraw Module

The ImageDraw 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 the aggdraw module.

Example: Draw a gray cross over an image

  1. from PIL import Image, ImageDraw
  2.  
  3. im = Image.open("hopper.jpg")
  4.  
  5. draw = ImageDraw.Draw(im)
  6. draw.line((0, 0) + im.size, fill=128)
  7. draw.line((0, im.size[1], im.size[0], 0), fill=128)
  8.  
  9. # write to stdout
  10. im.save(sys.stdout, "PNG")

Concepts

Coordinates

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.

Colors

To specify colors, you can use numbers or tuples just as you would use withPIL.Image.new() or PIL.Image.Image.putpixel(). For “1”,“L”, and “I” images, use integers. For “RGB” images, use a 3-tuple containinginteger values. For “F” images, use integer or floating point values.

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.

Color Names

See Color Names for the color names supported by Pillow.

Fonts

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 the ImageFontmodule.

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.

Example: Draw Partial Opacity Text

  1. from PIL import Image, ImageDraw, ImageFont
  2. # get an image
  3. base = Image.open('Pillow/Tests/images/hopper.png').convert('RGBA')
  4.  
  5. # make a blank image for the text, initialized to transparent text color
  6. txt = Image.new('RGBA', base.size, (255,255,255,0))
  7.  
  8. # get a font
  9. fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 40)
  10. # get a drawing context
  11. d = ImageDraw.Draw(txt)
  12.  
  13. # draw text, half opacity
  14. d.text((10,10), "Hello", font=fnt, fill=(255,255,255,128))
  15. # draw text, full opacity
  16. d.text((10,60), "World", font=fnt, fill=(255,255,255,255))
  17.  
  18. out = Image.alpha_composite(base, txt)
  19.  
  20. out.show()

Functions

  • class PIL.ImageDraw.Draw(im, mode=None)
  • 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.

Methods

  • PIL.ImageDraw.ImageDraw.getfont()
  • Get the current default font.

返回:An image font.

  • PIL.ImageDraw.ImageDraw.arc(xy, start, end, fill=None, width=0)
  • 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], where x1 >= x0 and y1 >=
    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.

5.3.0 新版功能.

  • PIL.ImageDraw.ImageDraw.bitmap(xy, bitmap, fill=None)
  • 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 doing image.paste(xy, color, bitmap).

To paste pixel data into an image, use thepaste() method on the image itself.

  • PIL.ImageDraw.ImageDraw.chord(xy, start, end, fill=None, outline=None, width=0)
  • Same as arc(), 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], where x1 >= x0 and y1 >=
    y0
    .
  • outline – Color to use for the outline.
  • fill – Color to use for the fill.
  • width
    The line width, in pixels.

5.3.0 新版功能.

  • PIL.ImageDraw.ImageDraw.ellipse(xy, fill=None, outline=None, width=0)
  • 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], where x1 >= x0and y1 >= y0.
  • outline – Color to use for the outline.
  • fill – Color to use for the fill.
  • width
    The line width, in pixels.

5.3.0 新版功能.

  • PIL.ImageDraw.ImageDraw.line(xy, fill=None, width=0, joint=None)
  • Draws a line between the coordinates in the xy list.

参数:

  • 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.

1.1.5 新版功能.

注解

This option was broken until version 1.1.6.

  • joint
    • Joint type between a sequence of lines. It can be “curve”,
    • for rounded edges, or None.

5.3.0 新版功能.

  • PIL.ImageDraw.ImageDraw.pieslice(xy, start, end, fill=None, outline=None, width=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], where x1 >= x0 and y1 >=
    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.

5.3.0 新版功能.

  • PIL.ImageDraw.ImageDraw.point(xy, fill=None)
  • 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.
  • PIL.ImageDraw.ImageDraw.polygon(xy, fill=None, outline=None)
  • Draws a polygon.

The polygon outline consists of straight lines between the givencoordinates, plus a straight line between the last and the firstcoordinate.

参数:

  • xy – Sequence of either 2-tuples like [(x, y), (x, y), …] ornumeric values like [x, y, x, y, …].
  • outline – Color to use for the outline.
  • fill – Color to use for the fill.
  • PIL.ImageDraw.ImageDraw.rectangle(xy, fill=None, outline=None, width=0)
  • Draws a rectangle.

参数:

  • xy – Two points to define the bounding box. Sequence of either[(x0, y0), (x1, y1)] or [x0, y0, x1, y1]. The second pointis just outside the drawn rectangle.
  • outline – Color to use for the outline.
  • fill – Color to use for the fill.
  • width
    The line width, in pixels.

5.3.0 新版功能.

  • PIL.ImageDraw.ImageDraw.shape(shape, fill=None, outline=None)

警告

This method is experimental.

Draw a shape.

  • PIL.ImageDraw.ImageDraw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align="left", direction=None, features=None, language=None, stroke_width=0, stroke_fill=None)
  • Draws the string at the given position.

参数:

  • xy – Top left corner of the text.
  • text – Text to be drawn. If it contains any newline characters,the text is passed on to multiline_text()
  • fill – Color to use for the text.
  • font – An ImageFont instance.
  • spacing – If the text is passed on to multiline_text(),the number of pixels between lines.
  • align – If the text is passed on to multiline_text(),“left”, “center” or “right”.
  • direction
    Direction of the text. It can be ‘rtl’ (right toleft), ‘ltr’ (left to right) or ‘ttb’ (top to bottom).Requires libraqm.

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, seehttps://docs.microsoft.com/en-us/typography/opentype/spec/featurelistRequires libraqm.

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 a _BCP 47 language code_Requires libraqm.

6.0.0 新版功能.

  • stroke_width
    The width of the text stroke.

6.2.0 新版功能.

  • stroke_fill
    • Color to use for the text stroke. If not given, will default to
    • the fill parameter.

6.2.0 新版功能.

  • PIL.ImageDraw.ImageDraw.multilinetext(_xy, text, fill=None, font=None, anchor=None, spacing=0, align="left", direction=None, features=None, language=None)
  • Draws the string at the given position.

参数:

  • xy – Top left corner of the text.
  • text – Text to be drawn.
  • fill – Color to use for the text.
  • font – An ImageFont instance.
  • spacing – The number of pixels between lines.
  • align – “left”, “center” or “right”.
  • direction
    Direction of the text. It can be ‘rtl’ (right toleft), ‘ltr’ (left to right) or ‘ttb’ (top to bottom).Requires libraqm.

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, seehttps://docs.microsoft.com/en-us/typography/opentype/spec/featurelistRequires libraqm.

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 a _BCP 47 language code_Requires libraqm.

6.0.0 新版功能.

  • PIL.ImageDraw.ImageDraw.textsize(text, font=None, spacing=4, direction=None, features=None, language=None, stroke_width=0)
  • Return the size of the given string, in pixels.

参数:

  • text – Text to be measured. If it contains any newline characters,the text is passed on to multiline_textsize()
  • font – An ImageFont instance.
  • spacing – If the text is passed on to multiline_textsize(),the number of pixels between lines.
  • direction
    Direction of the text. It can be ‘rtl’ (right toleft), ‘ltr’ (left to right) or ‘ttb’ (top to bottom).Requires libraqm.

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, seehttps://docs.microsoft.com/en-us/typography/opentype/spec/featurelistRequires libraqm.

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 a _BCP 47 language code_Requires libraqm.

6.0.0 新版功能.

  • stroke_width
    The width of the text stroke.

6.2.0 新版功能.

  • PIL.ImageDraw.ImageDraw.multilinetextsize(_text, font=None, spacing=4, direction=None, features=None, language=None, stroke_width=0)
  • Return the size of the given string, in pixels.

参数:

  • text – Text to be measured.
  • font – An ImageFont instance.
  • spacing – The number of pixels between lines.
  • direction
    Direction of the text. It can be ‘rtl’ (right toleft), ‘ltr’ (left to right) or ‘ttb’ (top to bottom).Requires libraqm.

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, seehttps://docs.microsoft.com/en-us/typography/opentype/spec/featurelistRequires libraqm.

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 a _BCP 47 language code_Requires libraqm.

6.0.0 新版功能.

  • stroke_width
    The width of the text stroke.

6.2.0 新版功能.

  • PIL.ImageDraw.getdraw(im=None, hints=None)

警告

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.
  • PIL.ImageDraw.floodfill(image, xy, value, border=None, thresh=0)

警告

This method is experimental.

Fills a bounded region with a given color.

参数:

  • image – Target image.
  • xy – Seed position (a 2-item coordinate tuple).
  • 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 of non-homogeneous, but similar, colors.