note 105593 added to function.imagettfbbox
| From: | jodybrabec at gmail dot com | Date: | Tue, 30 Aug 2011 22:39:42 +0000 |
| Subject: | note 105593 added to function.imagettfbbox | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-182838@lists.php.net to get a copy of this message | ||
Very CLEAR version of func., with example, and where to download fonts....
<?php
function calculateTextBox($text,$fontFile,$fontSize,$fontAngle) {
/************
simple function that calculates the *exact* bounding box (single pixel precision).
The function returns an associative array with these keys:
left, top: coordinates you will pass to imagettftext
width, height: dimension of the image you have to create
*************/
$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) - 1,
"top" => abs($minY) - 1,
"width" => $maxX - $minX,
"height" => $maxY - $minY,
"box" => $rect
);
}
// Example usage - gif image output
$text_string = "Hullo World";
$font_ttf = "./fonts/arial.ttf"; // Download http://sugarscript.com/scripts/text_2_img/fonts.zip
$font_size = 22;
$text_angle = 0;
$text_padding = 10; // Img padding - around text
$the_box = calculateTextBox($text_string, $font_ttf, $font_size, $text_angle);
$imgWidth = $the_box["width"] + $text_padding;
$imgHeight = $the_box["height"] + $text_padding;
$image = imagecreate($imgWidth,$imgHeight);
imagefill($image, imagecolorallocate($image,200,200,200));
$color = imagecolorallocate($image,0,0,0);
imagettftext($image,
$font_size,
$text_angle,
$the_box["left"] + ($imgWidth / 2) - ($the_box["width"] / 2),
$the_box["top"] + ($imgHeight / 2) - ($the_box["height"] / 2),
$color,
$font_ttf,
$text_string);
header("Content-Type: image/gif");
imagegif($image);
imagedestroy($image);
?>
[ remember: No spaces before or after the <?php ... ?> tag, because of header() call, you
Roast! ]
----
Server IP: 69.147.83.197
Probable Submitter: 128.196.6.46
----
Manual Page -- http://www.php.net/manual/en/function.imagettfbbox.php
Edit -- https://master.php.net/note/edit/105593
Del: integrated -- https://master.php.net/note/delete/105593/integrated
Del: useless -- https://master.php.net/note/delete/105593/useless
Del: bad code -- https://master.php.net/note/delete/105593/bad+code
Del: spam -- https://master.php.net/note/delete/105593/spam
Del: non-english -- https://master.php.net/note/delete/105593/non-english
Del: in docs -- https://master.php.net/note/delete/105593/in+docs
Del: other reasons-- https://master.php.net/note/delete/105593
Reject -- https://master.php.net/note/reject/105593
Search -- https://master.php.net/manage/user-notes.php