Font: lokicola.ttf
Font Size: 100
Text: DJ Mike
Array
(
[characterWidth] => 100
[characterHeight] => 100
[ascender] => 81
[descender] => -38
[textWidth] => 345
[textHeight] => 118
[maxHorizontalAdvance] => 144
[boundingBox] => Array
(
[x1] => -21
[y1] => -12
[x2] => 89
[y2] => 79
)
[originX] => 322
[originY] => 0
)
<?php
/*
Center text horizantally and vertically with the descender below the baseline and the ascender above the baseline..
*/
$bg = "white";
$type = "png";
$border = 40;
$font = "lokicola.ttf";
$font_color = "blue";
$font_size = 100;
$text = "DJ Mike";
$image = new imagick(); # new image object
$annotate = new imagickdraw(); # new draw object
$annotate->setfont("$font");
$annotate->setFontSize($font_size);
$annotate->setfillcolor("$font_color");
$annotate->setgravity(imagick::GRAVITY_CENTER);
# get font metrics at current settings
$metrics = $image->queryFontMetrics( $annotate, $text );
# Calculate image size based on font metrics and $border
$w = $metrics[textWidth]+$border*2;
# $metrics[descender] is negative number so add it.
$h = $metrics[textHeight]+$metrics[descender]+$border*2;
# make background image
$image->newimage( $w, $h, $bg);
# Draw box
$rectangle = new imagickdraw();
$rectangle->setfillcolor("#aaaaaa");
$rectangle->rectangle( $border, $border, $w-$border, $h-$border );
$image->drawimage($rectangle);
# Draw the baseline
$x1 = $border;
$y = $border+$metrics[textHeight]+$metrics[descender];
$x2 = $metrics[textWidth]+$border*2-$border;
$line = new imagickdraw();
$line->setfillcolor("red");
$line->setstrokecolor("red");
$line->setstrokewidth(4);
$line->setStrokeLineCap(imagick::LINECAP_ROUND);
$line->line( $x1, $y, $x2, $y);
$image->drawimage($line);
# change line color and move it up the ascender height
$y = $y-$metrics[ascender];
$line->setfillcolor("green");
$line->setstrokecolor("green");
$line->line( $x1, $y, $x2, $y);
$image->drawimage($line);
# Annotate
# Move text down 1/2 descender length to sit it on the baseline
$offset = -$metrics[descender]/2;
$image->annotateImage( $annotate, 0, $offset, 0, $text );
# output to browser
$image->setimageformat("$type");
header( "Content-Type: image/$type" );
echo $image;
?>