A few notes about text bounding boxes which, I hope, will help in precise placement of your text.
Suppose I have the text string "The lazy fox" which I want to display using 150pt Vivaldi . My image is 4896 x 3672 and I want the text placed at the bottom right but 250 pixels from the edges of the image.
$box = imagettfbbox(150,0,'c:/windows/fonts/vivaldii.ttf','The lazy fox');
gives this array of coordinates of the four corners
$box = Array
(
[0] => 23
[1] => 55
[2] => 871
[3] => 55
[4] => 871
[5] => -140
[6] => 23
[7] => -140
)
You may wonder why it can't just give a rectangle from (0,0) to (width, height) to make sizing simple, but there is extra information to be extracted from the array
Text width = (871 - 23) = 848
Text height = 55 - (-140) = 195
The baseline will be 140px from the top
The text is offset 23 px to the right.
My text, therefore, will be in a rectangle 848 x 195 positioned 250 px from right and bottom edges.
The top left x coord of the rectangle will be (4896 - 250 - 848) = 3798 and top left y coord will be (3672 - 250 - 195) = 3227.
However, to land the text precisely into this area we position it on the baseline and at the required x offset, ie (3798 - 23 , 3227 + 140) = (3775, 3367).
I use a simple custom function to assist with this process
function metrics($font, $fsize, $str)
{
$box = imagettfbbox($fsize, 0, $font, $str);
$ht = abs($box[5] - $box[1]);
$wd = abs($box[4] - $box[0]);
$base = -$box[5];
$tx = -$box[0];
return [ 'width' => $wd,
'height' => $ht,
'ascent' => $base,
'offsetx' => $tx
];
}
$box = metrics ('c:/windows/fonts/vivaldii.ttf', 150, 'The lazy fox');
$box = Array
(
[width] => 848
[height] => 195
[ascent] => 140
[offsetx] => -23
)