PHP-GD: Trying to center text but it is showing up horizontally off-center

57 Views Asked by At

The PHP code below is supposed to center the letter "M" vertically and horizontally. Vertically it is perfectly centered, but horizontally it is off.

What is really strange is that the offset appears correct, but it seems to be placed at a different coordinate then what I am telling it. (Correct starting X offset should be 10, but it appears to be placed after 16 pixels in).

M text off-center

<?php

header('Content-Type: image/png');

$image = imagecreatetruecolor(100, 400);

$font_size = 92;
$font = "RobotoCondensed-Bold.ttf"; // FILE PATH TO FONT
$angle = 0;
$text = "M";
$red = imagecolorallocate($image, 255, 0, 0);
$white = imagecolorallocate($image, 255, 255, 255);

// Get image dimensions
$image_width = imagesx($image);
$image_height = imagesy($image);

$text_bound = imageftbbox($font_size, $angle, $font, $text);

//Get the text upper, lower, left and right corner bounds
$lower_left_x =  $text_bound[0]; 
$lower_left_y =  $text_bound[1];
$lower_right_x = $text_bound[2];
$lower_right_y = $text_bound[3];
//$upper_right_x = $text_bound[4];
$upper_right_y = $text_bound[5];
//$upper_left_x =  $text_bound[6];
//$upper_left_y =  $text_bound[7];


//Get text Width and text height
$text_width =  $lower_right_x - $lower_left_x; //or  $upper_right_x - $upper_left_x
$text_height = $lower_right_y - $upper_right_y; //or  $lower_left_y - $upper_left_y

//Get the starting position for centering
$start_x_offset = ($image_width - $text_width) / 2;
$start_y_offset = ($image_height + $text_height) / 2;

// Add text to image
imagettftext($image, $font_size, $angle, $start_x_offset, $start_y_offset, $red, $font, $text);


// Debug stats
$debug_text = "text_width:[" . $text_width . "]\n";
$debug_text .= "text_height:[" . $text_height . "]\n";
$debug_text .= "start_x_offset:[" . $start_x_offset . "]\n";
$debug_text .= "start_y_offset:[" . $start_y_offset . "]\n";
imagettftext($image, 8, 0, 0, 300, $white, $font, $debug_text);


imagepng($image);
imagedestroy($image);

?>
0

There are 0 best solutions below