Novis\Image\Font::fromBytes
Novis\Image\Font::fromBytes(tainted bytes $data): FontNovis\Image\Font::fromBytes( tainted bytes $data, ): Font
Makes a Font from the bytes of a font file, so that Image::withText and Image::measureText can use it.
Font::fromBytes takes the bytes of a TrueType (.ttf) or OpenType (.otf) file. The bytes may be tainted bytes, such as an uploaded font. There are no system fonts, so your program loads the file itself. Make the Font once and use it for many images.
Font::fromBytes checks only that the bytes are at least 12 bytes long and start like a font file. Other bytes throw a ParseError. The rest of the file is read when an image is drawn or text is measured. A font file with broken tables throws a ParseError then.
The examples below load a font and measure a word, catch bytes that are not a font, and use one font for several images.
Parameters
$datatainted bytes
Return value
Returns Font.
Changelog
| Version | Change |
|---|---|
0.0.6 | Image::encode, the pixels of Image::raw, each file of Image::encodeVariants and the result of Pages::merge are tainted bytes. An image or a PDF file may be an upload. Font::fromBytes takes tainted bytes. |
Examples
Load a font
<?nvs// Shows how to make a `Font` from the bytes of a font file and measure a word with it.use Novis\Image\Font;use Novis\Image\Image;
require 'fonts/box-font.nvs';
// `BoxFont::load` calls `Font::fromBytes` with the bytes of a small font file.Font $font = BoxFont::load();
// This prints 24 and 10.var $size = Image::measureText('Shop', $font, { size: 10.0 });echo $size->width, "\n", $size->height, "\n";2410Bytes that are not a font
<?nvs// Shows how to catch an uploaded file that is not a font.use Novis\Image\Color;use Novis\Image\Font;use Novis\Image\Image;
// A PNG file starts with other bytes than a font file.tainted bytes $upload = Image::create(4, 4, Color::hex('#ffffff'))->encode();
// This prints "not a font".try { Font $font = Font::fromBytes($upload); echo "a font\n";} catch (ParseError $e) { echo "not a font\n";}not a fontOne font many badges
<?nvs// Shows how to load a font once and draw with it on several images.use Novis\Image\Color;use Novis\Image\Font;use Novis\Image\Image;
require 'fonts/box-font.nvs';
Font $font = BoxFont::load();array<string> $labels = ['Sale', 'New', 'Shop'];
// Each badge is as wide as its label, plus 4 pixels on each side. This prints 32, 26 and 32.foreach ($labels as string $label) { uint $width = Image::measureText($label, $font, { size: 10.0 })->width + 8; tainted bytes $png = Image::create($width, 18, Color::hex('#2e7d32')) ->withText($label, $font, { size: 10.0, color: Color::hex('#ffffff') }) ->encode(); echo Image::info($png)->width, "\n";}322632