note 97357 added to function.imagettfbbox
| From: | blackbart at simail dot it | Date: | Thu, 15 Apr 2010 18:12:18 +0000 |
| Subject: | note 97357 added to function.imagettfbbox | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-168290@lists.php.net to get a copy of this message | ||
I wrote a 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
function
calculateTextBox($font_size, $font_angle, $font_file, $text) {
$box = imagettfbbox($font_size, $font_angle, $font_file, $text);
if( !$box )
return false;
$min_x = min( array($box[0], $box[2], $box[4], $box[6]) );
$max_x = max( array($box[0], $box[2], $box[4], $box[6]) );
$min_y = min( array($box[1], $box[3], $box[5], $box[7]) );
$max_y = max( array($box[1], $box[3], $box[5], $box[7]) );
$width = ( $max_x - $min_x );
$height = ( $max_y - $min_y );
$left = abs( $min_x ) + $width;
$top = abs( $min_y ) + $height;
// to calculate the exact bounding box i write the text in a large image
$img = @imagecreatetruecolor( $width << 2, $height << 2 );
$white = imagecolorallocate( $img, 255, 255, 255 );
$black = imagecolorallocate( $img, 0, 0, 0 );
imagefilledrectangle($img, 0, 0, imagesx($img), imagesy($img), $black);
// for sure the text is completely in the image!
imagettftext( $img, $font_size,
$font_angle, $left, $top,
$white, $font_file, $text);
// start scanning (0=> black => empty)
$rleft = $w4 = $width<<2;
$rright = 0;
$rbottom = 0;
$rtop = $h4 = $height<<2;
for( $x = 0; $x < $w4; $x++ )
for( $y = 0; $y < $h4; $y++ )
if( imagecolorat( $img, $x, $y ) ){
$rleft = min( $rleft, $x );
$rright = max( $rright, $x );
$rtop = min( $rtop, $y );
$rbottom = max( $rbottom, $y );
}
// destroy img and serve the result
imagedestroy( $img );
return array( "left" => $left - $rleft,
"top" => $top - $rtop,
"width" => $rright - $rleft + 1,
"height" => $rbottom - $rtop + 1 );
}
----
Server IP: 81.88.49.8
Probable Submitter: 79.7.195.28
----
Manual Page -- http://www.php.net/manual/en/function.imagettfbbox.php
Edit -- https://master.php.net/note/edit/97357
Del: integrated -- https://master.php.net/note/delete/97357/integrated
Del: useless -- https://master.php.net/note/delete/97357/useless
Del: bad code -- https://master.php.net/note/delete/97357/bad+code
Del: spam -- https://master.php.net/note/delete/97357/spam
Del: non-english -- https://master.php.net/note/delete/97357/non-english
Del: in docs -- https://master.php.net/note/delete/97357/in+docs
Del: other reasons-- https://master.php.net/note/delete/97357
Reject -- https://master.php.net/note/reject/97357
Search -- https://master.php.net/manage/user-notes.php