PHP 8.5.0 Alpha 2 available for testing

Voting

: six plus one?
(Example: nine)

The Note You're Voting On

beosman at gmail dot com
16 years ago
I was viewing the code for calculate the box of a text for a given font but I do not found one that works fine with different angles from zero, so I have made a function simpler than above:

<?php

function calculateTextBox($text,$fontFile,$fontSize,$fontAngle) {
$rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text);

$minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
$maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
$minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
$maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7]));

return array(
"left" => abs($minX),
"top" => abs($minY),
"width" => $maxX - $minX,
"height" => $maxY - $minY,
"box" => $rect
);
}

?>

With this function you can center an angled string in any image:

<?php

$mystring
= "Hello world!";

$imgWidth = 300;
$imgHeight = 150;

$image = imagecreate($imgWidth,$imgHeight);
imagefill($image,imagecolorallocate($image,200,200,200));

$box = calculateTextBox($mystring,"./Verdana.ttf",15,45);
$color = imagecolorallocate($image,0,0,0);
imagettftext($image,
15,
45,
$box["left"] + ($imgWidth / 2) - ($box["width"] / 2),
$box["top"] + ($imgHeight / 2) - ($box["height"] / 2),
$color,
"./Verdana.ttf",
$mystring);

header("Content-Type: image/x-png");
imagepng($im);
imagedestroy($im);

?>

<< Back to user notes page

To Top