Voting

: max(eight, four)?
(Example: nine)

The Note You're Voting On

mike at delenk dot net
17 years ago
The examples in function imagettfbbox() gave me many problems because of misunderstand of how the text is positionned in the box.

So I did a new example:
- writing a text
- in the correct position in its box
- with a padding around

Enjoy !
Mike

<?

// some settings
$angle = 0;
$text = 'Ühg 0123456789';
$font_face = dirname(__FILE__).'/verdana.ttf'; // put the file in the same directory
$font_size = 9; //(int) pixels in GD 1, or points in GD 2

// retrieves box frame
$box = imagettfbbox($font_size, 0, $font_face, $text);
$bottom_left_x = $box[0]; // used below
$bottom_left_y = $box[1]; // used below
$bottom_right_x = $box[2]; // used below
$bottom_right_y = $box[3];
$top_right_x = $box[4];
$top_right_y = $box[5];
$top_left_x = $box[6];
$top_left_y = $box[7]; // used below

// define width and height of the text box
$box_w = abs($bottom_left_x) + abs($bottom_right_x);
$box_h = abs($bottom_left_y) + abs($top_left_y);

// add padding
$padding_x = 5;
$padding_y = 5;
$box_w = $box_w + 2 * $padding_x;
$box_h = $box_h + 2 * $padding_y;

// origin of the text = baseline of the first char
$text_x = abs($bottom_left_x) -1 + $padding_x;
$text_y = $box_h -1 - abs($bottom_left_y) - $padding_y;

// mysterious correction for the characters going low like pgjq
if(abs($bottom_left_y) <= 1) $box_h--;

// create the image
$img = imagecreatetruecolor($box_w, $box_h);

// define some colors
$white = imagecolorallocate($img,255,255,255);
$black = imagecolorallocate($img,0,0,0);
$lightgrey = imagecolorallocate($img, 200, 200, 200);
$grey = imagecolorallocate($img,100,100,100);
$yellow = imagecolorallocate($img, 0xFF, 0xFF, 0x00);

// attribute colors
$font_color = $black;
$padding_color = $lightgrey;
$background_color = $yellow;

// fill image with background color
imagefill($img, 0, 0, $background_color);

// fill image with padding color
imagefilledrectangle($img, 0, 0, $box_w, $padding_y - 1, $padding_color); // top
imagefilledrectangle($img, 0, 0, $padding_x - 1, $box_h - 1, $padding_color); // left
imagefilledrectangle($img, 0, $box_h - $padding_y -1, $box_w, $box_h - 1, $padding_color); // bottom
imagefilledrectangle($img, $box_w - $padding_x, 0, $box_w - 1, $box_h - 1, $padding_color); // right

//write text
imagettftext($img, $font_size, 0, $text_x, $text_y, $font_color, $font_face, $text);

//rotate image
if ($angle > 0) $img = imagerotate($img, $angle, $white);

// send header
header("Content-type: image/gif");

//sends image
imagegif($img);
imagedestroy($img);
?>

<< Back to user notes page

To Top