Imager::Font(3pm)
β¨ NAME β¨
okay bestie, this is Imager::Font(3pm) from the User Contributed Perl Documentation β the manual page for Imager::Font, aka Font handling for Imager. π
π SYNOPSIS π
hereβs the quick-start stack, no cap:
use Imager;
$t1font = Imager::Font->new(file => 'pathtofont.pfb');
$ttfont = Imager::Font->new(file => 'pathtofont.ttf');
$w32font = Imager::Font->new(face => 'Times New Roman');
$blue = Imager::Color->new("#0000FF");
$font = Imager::Font->new(file => 'pathtofont.ttf',
color => $blue,
size => 30);
($neg_width,
$global_descent,
$pos_width,
$global_ascent,
$descent,
$ascent,
$advance_width,
$right_bearing) = $font->bounding_box(string=>"Foo");
my $bbox_object = $font->bounding_box(string=>"Foo");
# documented in Imager::Draw
$img->string(font => $font,
text => "Model-XYZ",
x => 15,
y => 40,
size => 40,
color => $red,
aa => 1);
π¦ DESCRIPTION π¦
This module manages the font object; the one returned by Imager::Font->new will typically be of a class derived from Imager::Font. β¨
π new π
This creates a font object to pass to functions that take a font argument. π«Ά
$font = Imager::Font->new(file => 'denmark.ttf',
index => 0,
color => $blue,
size => 30,
aa => 1);
This creates a font which is the TrueType font denmark.ttf. Its default color is $blue, default size is 30 pixels, and itβs rendered anti-aliased by default. Imager can see which type of font a file is by looking at the suffix of the file name for the font. A suffix of ttf is taken to mean a TrueType font while a suffix of pfb is taken to mean a Type 1 Postscript font. If Imager cannot tell which type a font is you can tell it explicitly by using the type parameter:
$t1font = Imager::Font->new(file => 'fruitcase', type => 't1');
$ttfont = Imager::Font->new(file => 'arglebarf', type => 'tt');
The index parameter is used to select a single face from a font file containing more than one face, for example, from a Macintosh font suitcase or a .dfont file. π
If any of the color, size or aa parameters are omitted when calling Imager::Font->new() they take the following values:
color => Imager::Color->new(255, 0, 0, 0); # this default should be changed
size => 15
aa => 0
index => 0
To use Win32 fonts supply the face name of the font:
$font = Imager::Font->new(face=>'Arial Bold Italic');
There isnβt any access to other logical font attributes, but this typically isnβt necessary for Win32 TrueType fonts, since you can construct the full name of the font as above. π
Other logical font attributes may be added if there is sufficient demand.
Parameters:
fileβ name of the file to load the font from.faceβ face name. This is used only under Win32 to create a GDI based font. This is ignored if thefileparameter is supplied.typeβ font driver to use. Currently the permitted values for this are:ttβ FreeType 1.x driver. Supports TrueType (.ttf) fonts.t1β T1 Lib driver. Supports Postscript Type 1 fonts. Allows for synthesis of underline, strikethrough and overline.ft2β FreeType 2.x driver. Supports many different font formats. Also supports thetransform()method.
colorβ the default color used with this font. Default: red.sizeβ the default size used with this font. Default: 15.utf8β if non-zero then text supplied to$img->string(...)and$font->bounding_box(...)is assumed to be UTF-8 encoded by default.alignβ the default value for the$img->string(...)alignparameter. Default: 1.vlayoutβ the default value for the$img->string(...)vlayoutparameter. Default: 0.aaβ the default value for the$im->string(...)aaparameter. Default: 0.indexβ for font file containing multiple fonts this selects which font to use. This is useful for MacintoshDFON(.dfont) and suitcase font files.
If you want to use a suitcase font you will need to tell Imager to use the FreeType 2.x driver by setting type to 'ft2':
my $font = Imager::Font->new(file=>$file, index => 1, type=>'ft2')
or die Imager->errstr;
Returns the new font object on success. Returns undef on failure and sets an error message readable with Imager->errstr. π
π¦ bounding_box() π¦
Returns the bounding box for the specified string. Example:
my ($neg_width,
$global_descent,
$pos_width,
$global_ascent,
$descent,
$ascent,
$advance_width,
$right_bearing) = $font->bounding_box(string => "A Fool");
my $bbox_object = $font->bounding_box(string => "A Fool");
$neg_widthβ the relative start of the string. In some cases this can be a negative number, in that case the first letter stretches to the left of the starting position that is specified in thestringmethod of the Imager class.$global_descentβ how far down the lowest letter of the entire font reaches below the baseline (this is oftenj).$pos_widthβ how wide the string from the starting position is. The total width of the string is"$pos_width-$neg_width".$descent,$ascentβ the same as$global_descentand$global_ascentexcept that they are only for the characters that appear in the string.$advance_widthβ the distance from the start point that the next string output should start at, this is often the same as$pos_width, but can be different if the final character overlaps the right side of its character cell.$right_bearingβ The distance from the right side of the final glyph to the end of the advance width. If the final glyph overflows the advance width this value is negative.
Obviously we can stuff all the results into an array just as well:
@metrics = $font->bounding_box(string => "testing 123");
Note that extra values may be added, so $metrics[-1] isnβt supported. Itβs possible to translate the output by passing a coordinate to the bounding box method:
@metrics = $font->bounding_box(string => "testing 123", x=>45, y=>34);
This gives the bounding box as if the string had been put down at (x,y). By giving bounding_box 'canon' as a true value itβs possible to measure the space needed for the string:
@metrics = $font->bounding_box(string=>"testing",size=>15,canon=>1);
This returns the same values in $metrics[0] and $metrics[1], but:
$bbox[2] - horizontal space taken by glyphs
$bbox[3] - vertical space taken by glyphs
Returns an Imager::Font::BBox object in scalar context, so you can avoid all those confusing indexes. This has methods as named above, with some extra convenience methods. π
Parameters are:
stringβ the string to calculate the bounding box for. Required.sizeβ the font size to use. Default: value set inImager::Font->new(), or 15.sizewβ the font width to use. Default to the value of thesizeparameter.utf8β For drivers that support it, treat the string as UTF-8 encoded. For versions of perl that support Unicode (5.6 and later), this will be enabled automatically if the'string'parameter is already a UTF-8 string. See"UTF-8"for more information. Default: theutf8value passed toImager::Font->new(...)or 0.x,yβ offsets applied to@box[0..3]to give you an adjusted bounding box. Ignored in scalar context.canonβ if non-zero and thex,yparameters are not supplied, then$pos_widthand$global_ascentvalues will be returned as the width and height of the text instead.
On success returns either the list of bounds, or a bounding box object in scalar context. Returns an empty list or undef on failure and sets an error message readable with Imager->errstr.
The transformation matrix set by transform() has no effect on the result of this method β the bounds of the untransformed text is returned. π
πΈ string() πΈ
The $img->string(...) method is now documented in "string()" in Imager::Draw. π¦
π align(string=>$text,size=>$size,x=>...,y=>...,valign => ...,halign=>...) π
Higher level text output β outputs the text aligned as specified around the given point (x,y). β¨
# "Hello" centered at 100, 100 in the image.
my ($left, $top, $right, $bottom) =
$font->align(string=>"Hello",
x=>100, y=>100,
halign=>'center', valign=>'center',
image=>$image);
Takes the same parameters as $font->draw(), and the following extra parameters:
valignβ Possible values are:topβ Point is at the top of the text.bottomβ Point is at the bottom of the text.baselineβ Point is on the baseline of the text (default.)centerβ Point is vertically centered within the text.
halignleftβ the point is at the left of the text.startβ the point is at the start point of the text.centerβ the point is horizontally centered within the text.rightβ the point is at the right end of the text.endβ the point is at the end point of the text.
imageβ The image to draw to. Set toundefto avoid drawing but still calculate the bounding box.
Returns a list specifying the bounds of the drawn text on success. Returns an empty list on failure, if an image parameter was supplied the error message can be read with $image->errstr, otherwise itβs available as Imager->errstr. π«Ά
dpi()β no args? it just hands you the current dots-per-inch vibes, bestie.dpi(xdpi=>$xdpi, ydpi=>$ydpi)β set horizontal and vertical resolution separately, slay.dpi(dpi=>$dpi)β set both at once, one value, iconic.
Set or retrieve the spatial resolution of the image in dots per inch. The default is 72 dpi.
This isn't implemented for all font types yet β so if your fave driver ghosts you on this, that's why π.
Possible parameters are:
"xdpi","ydpi"β set the horizontal and vertical resolution in dots per inch."dpi"β set both horizontal and vertical resolution to this value.
Returns a list containing the previous "xdpi", "ydpi" values on success. Returns an empty list on failure, with an error message returned in "Imager->errstr".
transform()
$font->transform(matrix=>$matrix);
Applies a transformation to the font, where matrix is an array ref of numbers representing a 2 x 3 matrix:
[ $matrix->[0], $matrix->[1], $matrix->[2],
$matrix->[3], $matrix->[4], $matrix->[5] ]
Not all font types support transformations β those ones will return false, no cap.
It's possible that a driver will disable hinting if you use a transformation, to prevent discontinuities in the transformations. See the end of the test script t/t38ft2font.t for an example.
Currently only the ft2 (FreeType 2.x) driver supports the transform() method. π
See samples/slant_text.pl for a sample using this function.
Note that the transformation is done in font co-ordinates where y increases as you move up, not image co-ordinates where y decreases as you move up. tiny but important detail, bestie π«Ά
transform() has no effect on the results of "bounding_box()".
Returns true on success. Returns false on failure with the cause readable from "Imager->errstr".
has_chars(string=>$text)β checks if the characters in$textare defined by the font.
In a list context returns a list of true or false value corresponding to the characters in $text, true if the character is defined, false if not. In scalar context returns a string of "NUL" or non-"NUL" characters. Supports UTF-8 where the font driver supports UTF-8.
Not all fonts support this method (use $font->can("has_chars") to check.) lowkey always check, bestie π
On error, returns an empty list or undef in scalar context, and sets an error message readable with "Imager->errstr".
"string"β string of characters to check for. Required. Must contain at least one character. no empty strings, that's not the vibe."utf8"β For drivers that support it, treat the string as UTF-8 encoded. For versions of perl that support Unicode (5.6 and later), this will be enabled automatically if the'string'parameter is already a UTF-8 string. See"UTF-8"for more information. Default: the"utf8"value passed toImager::Font->new(...)or0.
face_name()β returns the internal name of the face. Not all font types support this method yet, so you should check with"$font->can("face_name")"before calling"face_name". better safe than sorry β¨
glyph_names(string=>$string [, utf8=>$utf8 ][, reliable_only=>0 ] );β returns a list of glyph names for each of the characters in the string. If the character has no name then"undef"is returned for the character.
Some font files do not include glyph names, in this case FreeType 2 will not return any names. FreeType 1 can return standard names even if there are no glyph names in the font.
FreeType 2 has an API function that returns true only if the font has "reliable glyph names", unfortunately this always returns false for TrueType fonts. This can avoid the check of this API by supplying "reliable_only" as 0. The consequences of using this on an unknown font may be unpredictable, since the FreeType documentation doesn't say how those name tables are unreliable, or how FT2 handles them. β οΈ like, proceed with caution, bestie.
Both FreeType 1.x and 2.x allow support for glyph names to not be included.
If the supplied "string" is marked as UTF-8 or the "utf8" parameter is true and the supplied string does not contain valid UTF-8, returns an empty string and set an error message readable from "Imager->errstr",
can_glyph_names()β as a class method, returns true if the underlying library supports returning glyph names.
As an object method, returns true if the supplied font supports returning glyph names. two moods, same icon π
drawβ this is used by Imager'sstring()method to implement drawing text. See"string()"in Imager::Draw.
π¦ MULTIPLE MASTER FONTS π¦
The FreeType 2 driver supports multiple master fonts:
is_mm()β test if the font is a multiple master font.mm_axes()β returns a list of the axes that can be changes in the font. Each entry is an array reference which contains:- Name of the axis.
- minimum value for this axis.
- maximum value for this axis
set_mm_coords(coords=>\@values)β blends an interpolated design from the master fonts.@valuesmust contain as many values as there are axes in the font.
For example, to select the minimum value in each axis:
my @axes = $font->mm_axes;
my @coords = map $_->[1], @axes;
$font->set_mm_coords(coords=>\@coords);
It's possible other drivers will support multiple master fonts in the future, check if your selected font object supports the is_mm() method using the can() method. future-proofing, we love to see it β¨
π UTF-8 π
There are 2 ways of rendering Unicode characters with Imager:
- For versions of perl that support it, use perl's native UTF-8 strings. This is the simplest method. main character energy, honestly.
- Hand build your own UTF-8 encoded strings. Only recommended if your version of perl has no UTF-8 support.
Imager won't construct characters for you, so if want to output Unicode character 00C3 "LATIN CAPITAL LETTER A WITH DIAERESIS", and your font doesn't support it, Imager will not build it from 0041 "LATIN CAPITAL LETTER A" and 0308 "COMBINING DIAERESIS". it does not do arts and crafts for you π
To check if a driver supports UTF-8 call the utf8() method:
utf8()β return true if the font supports UTF-8.
β¨ Native UTF-8 Support β¨
If your version of perl supports UTF-8 and the driver supports UTF-8, just use the $im->string() method, and it should do the right thing. periodt.
π Build your own π
In this case you need to build your own UTF-8 encoded characters.
For example:
$x = pack("C*", 0xE2, 0x80, 0x90); # character code 0x2010 HYPHEN
You need to be careful with versions of perl that have UTF-8 support, since your string may end up doubly UTF-8 encoded.
For example:
$x = "A\xE2\x80\x90\x41\x{2010}";
substr($x, -1, 0) = "";
# at this point $x is has the UTF-8 flag set, but has 5 characters,
# none, of which is the constructed UTF-8 character
The test script t/t38ft2font.t has a small example of this after the comment:
# an attempt using emulation of UTF-8
π DRIVER CONTROL π
If you don't supply a 'type' parameter to Imager::Font->new(), but you do supply a 'file' parameter, Imager will attempt to guess which font driver to used based on the extension of the font file.
Since some formats can be handled by more than one driver, a priority list is used to choose which one should be used, if a given format can be handled by more than one driver.
priorities
The current priorities can be retrieved with:
@drivers = Imager::Font->priorities();
You can set new priorities and save the old priorities with:
@old = Imager::Font->priorities(@drivers);
If you supply driver names that are not currently supported, they will be ignored.
Note that by default the priority list no longer includes"tt"and"t1", so typically you will need to haveImager::Font::FT2installed to create fonts with Imager.
my @old = Imager::Font->priorities(qw(tt ft2 t1));
register
Registers an extra font driver. Accepts the following parameters:
typeβ a brief identifier for the font driver. You can supply this value to"Imager::Font->new()"to create fonts of this type. Required.classβ the font class name. Imager will attempted to load this module by name. Required.filesβ a regular expression to match against file names. If supplied this must be a valid perl regular expression. If not supplied you can only create fonts of this type by supplying the"type"parameter to"Imager::Font->new()"descriptionβ a brief description of the font driver. Defaults to the value supplied in"class".
π AUTHOR π
Arnar M. Hrafnkelsson, addi@umich.edu And a great deal of help from others - see the README for a complete list. shoutout to the helpers, fr fr π«Ά
π BUGS π
The $pos_width member returned by the bounding_box() method has historically returned different values from different drivers. The FreeType 1.x and 2.x, and the Win32 drivers return the max of the advance width and the right edge of the right-most glyph. The Type 1 driver always returns the right edge of the right-most glyph.
The newer advance_width and right_bearing values allow access to any of the above. so you can get the deets either way, bestie β¨
β REVISION β
$Revision$
πΈ SEE ALSO πΈ
Imager(3), Imager::Font::FreeType2(3), Imager::Font::Type1(3), Imager::Font::Win32(3), Imager::Font::Truetype(3), Imager::Font::BBox(3)
and that's the whole page, bestie π this beauty is from perl v5.42.3, dated 2026-08-19, and it's Imager::Font(3pm) β go forth and make fonts iconic π
β¨
π¦ where this page comes from
- ubuntu stonking: libimager-perl 1.035+dfsg-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms