ImageFont
Module¶
The ImageFont
module defines a class with the same name. Instances of
this class store bitmap fonts, and are used with the
PIL.ImageDraw.ImageDraw.text()
method.
PIL uses its own font file format to store bitmap fonts, limited to 256 characters. You can use pilfont.py from pillow-scripts to convert BDF and PCF font descriptors (X window font formats) to this format.
Starting with version 1.1.4, PIL can be configured to support TrueType and OpenType fonts (as well as other font formats supported by the FreeType library). For earlier versions, TrueType support is only available as part of the imToolkit package.
Warning
To protect against potential DOS attacks when using arbitrary strings as
text input, Pillow will raise a ValueError
if the number of characters
is over a certain limit, MAX_STRING_LENGTH
.
This threshold can be changed by setting
MAX_STRING_LENGTH
. It can be disabled by setting
ImageFont.MAX_STRING_LENGTH = None
.
Example¶
from PIL import ImageFont, ImageDraw
draw = ImageDraw.Draw(image)
# use a bitmap font
font = ImageFont.load("arial.pil")
draw.text((10, 10), "hello", font=font)
# use a truetype font
font = ImageFont.truetype("arial.ttf", 15)
draw.text((10, 25), "world", font=font)
Functions¶
- PIL.ImageFont.load(filename: str) ImageFont [source]¶
Load a font file. This function loads a font object from the given bitmap font file, and returns the corresponding font object. For loading TrueType or OpenType fonts instead, see
truetype()
.- Parameters:
filename – Name of font file.
- Returns:
A font object.
- Raises:
OSError – If the file could not be read.
- PIL.ImageFont.load_path(filename: str | bytes) ImageFont [source]¶
Load font file. Same as
load()
, but searches for a bitmap font along the Python path.- Parameters:
filename – Name of font file.
- Returns:
A font object.
- Raises:
OSError – If the file could not be read.
- PIL.ImageFont.truetype(font: str | bytes | PathLike[str] | PathLike[bytes] | BinaryIO, size: float = 10, index: int = 0, encoding: str = '', layout_engine: Layout | None = None) FreeTypeFont [source]¶
Load a TrueType or OpenType font from a file or file-like object, and create a font object. This function loads a font object from the given file or file-like object, and creates a font object for a font of the given size. For loading bitmap fonts instead, see
load()
andload_path()
.Pillow uses FreeType to open font files. On Windows, be aware that FreeType will keep the file open as long as the FreeTypeFont object exists. Windows limits the number of files that can be open in C at once to 512, so if many fonts are opened simultaneously and that limit is approached, an
OSError
may be thrown, reporting that FreeType “cannot open resource”. A workaround would be to copy the file(s) into memory, and open that instead.This function requires the _imagingft service.
- Parameters:
font –
A filename or file-like object containing a TrueType font. If the file is not found in this filename, the loader may also search in other directories, such as:
The
fonts/
directory on Windows,/Library/Fonts/
,/System/Library/Fonts/
and~/Library/Fonts/
on macOS.~/.local/share/fonts
,/usr/local/share/fonts
, and/usr/share/fonts
on Linux; or those specified by theXDG_DATA_HOME
andXDG_DATA_DIRS
environment variables for user-installed and system-wide fonts, respectively.
size – The requested size, in pixels.
index – Which font face to load (default is first available face).
encoding –
Which font encoding to use (default is Unicode). Possible encodings include (see the FreeType documentation for more information):
”unic” (Unicode)
”symb” (Microsoft Symbol)
”ADOB” (Adobe Standard)
”ADBE” (Adobe Expert)
”ADBC” (Adobe Custom)
”armn” (Apple Roman)
”sjis” (Shift JIS)
”gb “ (PRC)
”big5”
”wans” (Extended Wansung)
”joha” (Johab)
”lat1” (Latin-1)
This specifies the character set to use. It does not alter the encoding of any text provided in subsequent operations.
layout_engine –
Which layout engine to use, if available:
ImageFont.Layout.BASIC
orImageFont.Layout.RAQM
. If it is available, Raqm layout will be used by default. Otherwise, basic layout will be used.Raqm layout is recommended for all non-English text. If Raqm layout is not required, basic layout will have better performance.
You can check support for Raqm layout using
PIL.features.check_feature()
withfeature="raqm"
.Added in version 4.2.0.
- Returns:
A font object.
- Raises:
OSError – If the file could not be read.
ValueError – If the font size is not greater than zero.
- PIL.ImageFont.load_default(size: float | None = None) FreeTypeFont | ImageFont [source]¶
If FreeType support is available, load a version of Aileron Regular, https://dotcolon.net/font/aileron, with a more limited character set.
Otherwise, load a “better than nothing” font.
Added in version 1.1.4.
- Parameters:
size –
The font size of Aileron Regular.
Added in version 10.1.0.
- Returns:
A font object.
Methods¶
- class PIL.ImageFont.ImageFont[source]¶
PIL font wrapper
- getbbox(text: str | bytes | bytearray, *args: Any, **kwargs: Any) tuple[int, int, int, int] [source]¶
Returns bounding box (in pixels) of given text.
Added in version 9.2.0.
- Parameters:
text – Text to render.
- Returns:
(left, top, right, bottom)
bounding box
- getlength(text: str | bytes | bytearray, *args: Any, **kwargs: Any) int [source]¶
Returns length (in pixels) of given text. This is the amount by which following text should be offset.
Added in version 9.2.0.
- getmask(text: str | bytes, mode: str = '', *args: Any, **kwargs: Any) Image.core.ImagingCore [source]¶
Create a bitmap for the text.
If the font uses antialiasing, the bitmap should have mode
L
and use a maximum value of 255. Otherwise, it should have mode1
.- Parameters:
text – Text to render.
mode –
Used by some graphics drivers to indicate what mode the driver prefers; if empty, the renderer may return either mode. Note that the mode is always a string, to simplify C-level implementations.
Added in version 1.1.5.
- Returns:
An internal PIL storage memory instance as defined by the
PIL.Image.core
interface module.
- class PIL.ImageFont.FreeTypeFont(font: str | bytes | PathLike[str] | PathLike[bytes] | BinaryIO, size: float = 10, index: int = 0, encoding: str = '', layout_engine: Layout | None = None)[source]¶
FreeType font wrapper (requires _imagingft service)
- font_variant(font: str | bytes | PathLike[str] | PathLike[bytes] | BinaryIO | None = None, size: float | None = None, index: int | None = None, encoding: str | None = None, layout_engine: Layout | None = None) FreeTypeFont [source]¶
Create a copy of this FreeTypeFont object, using any specified arguments to override the settings.
Parameters are identical to the parameters used to initialize this object.
- Returns:
A FreeTypeFont object.
- get_variation_axes() list[Axis] [source]¶
- Returns:
A list of the axes in a variation font.
- Raises:
OSError – If the font is not a variation font.
- get_variation_names() list[bytes] [source]¶
- Returns:
A list of the named styles in a variation font.
- Raises:
OSError – If the font is not a variation font.
- getbbox(text: str | bytes, mode: str = '', direction: str | None = None, features: list[str] | None = None, language: str | None = None, stroke_width: float = 0, anchor: str | None = None) tuple[float, float, float, float] [source]¶
Returns bounding box (in pixels) of given text relative to given anchor when rendered in font with provided direction, features, and language.
Use
getlength()
to get the offset of following text with 1/64 pixel precision. The bounding box includes extra margins for some fonts, e.g. italics or accents.Added in version 8.0.0.
- Parameters:
text – Text to render.
mode – Used by some graphics drivers to indicate what mode the driver prefers; if empty, the renderer may return either mode. Note that the mode is always a string, to simplify C-level implementations.
direction – Direction of the text. It can be ‘rtl’ (right to left), ‘ltr’ (left to right) or ‘ttb’ (top to bottom). Requires libraqm.
features – A list of OpenType font features to be used during text layout. This is usually used to turn on optional font features that are not enabled by default, for example ‘dlig’ or ‘ss01’, but can be also used to turn off default font features for example ‘-liga’ to disable ligatures or ‘-kern’ to disable kerning. To get all supported features, see https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm.
language – Language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a BCP 47 language code Requires libraqm.
stroke_width – The width of the text stroke.
anchor – The text anchor alignment. Determines the relative location of the anchor to the text. The default alignment is top left, specifically
la
for horizontal text andlt
for vertical text. See Text anchors for details.
- Returns:
(left, top, right, bottom)
bounding box
- getlength(text: str | bytes, mode: str = '', direction: str | None = None, features: list[str] | None = None, language: str | None = None) float [source]¶
Returns length (in pixels with 1/64 precision) of given text when rendered in 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 concatenated string due to kerning. If you need to adjust for kerning, include the following character and subtract its length.
For example, instead of
hello = font.getlength("Hello") world = font.getlength("World") hello_world = hello + world # not adjusted for kerning assert hello_world == font.getlength("HelloWorld") # may fail
use
hello = font.getlength("HelloW") - font.getlength("W") # adjusted for kerning world = font.getlength("World") hello_world = hello + world # adjusted for kerning assert hello_world == font.getlength("HelloWorld") # 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 adjust assert hello_world == draw.textlength("HelloWorld", font, features=["-kern"])
Added in version 8.0.0.
- Parameters:
text – Text to measure.
mode – Used by some graphics drivers to indicate what mode the driver prefers; if empty, the renderer may return either mode. Note that the mode is always a string, to simplify C-level implementations.
direction – Direction of the text. It can be ‘rtl’ (right to left), ‘ltr’ (left to right) or ‘ttb’ (top to bottom). Requires libraqm.
features – A list of OpenType font features to be used during text layout. This is usually used to turn on optional font features that are not enabled by default, for example ‘dlig’ or ‘ss01’, but can be also used to turn off default font features for example ‘-liga’ to disable ligatures or ‘-kern’ to disable kerning. To get all supported features, see https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm.
language –
Language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a BCP 47 language code Requires libraqm.
- Returns:
Either width for horizontal text, or height for vertical text.
- getmask(text: str | bytes, mode: str = '', direction: str | None = None, features: list[str] | None = None, language: str | None = None, stroke_width: float = 0, anchor: str | None = None, ink: int = 0, start: tuple[float, float] | None = None) Image.core.ImagingCore [source]¶
Create a bitmap for the text.
If the font uses antialiasing, the bitmap should have mode
L
and use a maximum value of 255. If the font has embedded color data, the bitmap should have modeRGBA
. Otherwise, it should have mode1
.- Parameters:
text – Text to render.
mode –
Used by some graphics drivers to indicate what mode the driver prefers; if empty, the renderer may return either mode. Note that the mode is always a string, to simplify C-level implementations.
Added in version 1.1.5.
direction –
Direction of the text. It can be ‘rtl’ (right to left), ‘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 text layout. This is usually used to turn on optional font features that are not enabled by default, for example ‘dlig’ or ‘ss01’, but can be also used to turn off default font features for example ‘-liga’ to disable ligatures or ‘-kern’ to disable kerning. To get all supported features, see https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm.
Added in version 4.2.0.
language –
Language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a BCP 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.
anchor –
The text anchor alignment. Determines the relative location of the anchor to the text. The default alignment is top left, specifically
la
for horizontal text andlt
for vertical text. See Text anchors for details.Added in version 8.0.0.
ink –
Foreground ink for rendering in RGBA mode.
Added in version 8.0.0.
start –
Tuple of horizontal and vertical offset, as text may render differently when starting at fractional coordinates.
Added in version 9.4.0.
- Returns:
An internal PIL storage memory instance as defined by the
PIL.Image.core
interface module.
- getmask2(text: str | bytes, mode: str = '', direction: str | None = None, features: list[str] | None = None, language: str | None = None, stroke_width: float = 0, anchor: str | None = None, ink: int = 0, start: tuple[float, float] | None = None, *args: Any, **kwargs: Any) tuple[Image.core.ImagingCore, tuple[int, int]] [source]¶
Create a bitmap for the text.
If the font uses antialiasing, the bitmap should have mode
L
and use a maximum value of 255. If the font has embedded color data, the bitmap should have modeRGBA
. Otherwise, it should have mode1
.- Parameters:
text – Text to render.
mode –
Used by some graphics drivers to indicate what mode the driver prefers; if empty, the renderer may return either mode. Note that the mode is always a string, to simplify C-level implementations.
Added in version 1.1.5.
direction –
Direction of the text. It can be ‘rtl’ (right to left), ‘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 text layout. This is usually used to turn on optional font features that are not enabled by default, for example ‘dlig’ or ‘ss01’, but can be also used to turn off default font features for example ‘-liga’ to disable ligatures or ‘-kern’ to disable kerning. To get all supported features, see https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm.
Added in version 4.2.0.
language –
Language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a BCP 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.
anchor –
The text anchor alignment. Determines the relative location of the anchor to the text. The default alignment is top left, specifically
la
for horizontal text andlt
for vertical text. See Text anchors for details.Added in version 8.0.0.
ink –
Foreground ink for rendering in RGBA mode.
Added in version 8.0.0.
start –
Tuple of horizontal and vertical offset, as text may render differently when starting at fractional coordinates.
Added in version 9.4.0.
- Returns:
A tuple of an internal PIL storage memory instance as defined by the
PIL.Image.core
interface module, and the text offset, the gap between the starting coordinate and the first marking
- getmetrics() tuple[int, int] [source]¶
- Returns:
A tuple of the font ascent (the distance from the baseline to the highest outline point) and descent (the distance from the baseline to the lowest outline point, a negative value)
- getname() tuple[str | None, str | None] [source]¶
- Returns:
A tuple of the font family (e.g. Helvetica) and the font style (e.g. Bold)
Constants¶
- class PIL.ImageFont.Layout[source]¶
- BASIC¶
Use basic text layout for TrueType font. Advanced features such as text direction are not supported.
- RAQM¶
Use Raqm text layout for TrueType font. Advanced features are supported.
Requires Raqm, you can check support using
PIL.features.check_feature()
withfeature="raqm"
.
- PIL.ImageFont.MAX_STRING_LENGTH¶
Set to 1,000,000, to protect against potential DOS attacks. Pillow will raise a
ValueError
if the number of characters is over this limit. The check can be disabled by settingImageFont.MAX_STRING_LENGTH = None
.