0

I have a script that is writing a text over an image. It works fine, but the text is aligned to the left.

I am trying to center the text horizontally, but not sure how can I do that.

Here is the code that I have at the moment

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

if (isset($_GET['text'])){$text = $_GET['text'];}else{$text = "";}

//font
$font = 'Ubuntu-Medium.ttf';
//font size
$font_size = 18;
//image width
$width = 400;
//text margin
$margin = 90;


//explode text by words
$text_a = explode(' ', $text);
$text_new = '';
foreach($text_a as $word){
    //Create a new text, add the word, and calculate the parameters of the text
    $box = imagettfbbox($font_size, 0, $font, $text_new.' '.$word);
    //if the line fits to the specified width, then add the word with a space, if not then add word with new line
    if($box[2] > $width - $margin*2){
        $text_new .= "\n".$word;
    } else {
        $text_new .= " ".$word;
    }
}
//trip spaces
$text_new = trim($text_new);
//new text box parameters
$box = imagettfbbox($font_size, 0, $font, $text_new);
//new text height
$height = $box[1] + $font_size + $margin * 2;

//create image
$im = imagecreatefromjpeg('source.jpg'); 
//create colors

$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 51, 95, 32);
//color image
imagefilledrectangle($im, 0, 0, $width, $black); 

// determine the size of the text so we can center it
$box = imagettfbbox($font_size, 0, $font, $text_new);
$text_width = abs($box[2]) - abs($box[0]);
$text_height = abs($box[5]) - abs($box[3]);
$image_width = imagesx($im);
$image_height = imagesy($im);
$x = ($image_width - $text_width) / 2;
$y = ($image_height + $text_height) / 2;

//add text to image
imagettftext($im, $font_size, 0, $x, $y, $black, $font, $text_new);

//return image
imagepng($im);
//frees any memory associated with image
imagedestroy($im);

Any ideas on how can I center the text?

I already centered the box that the text is placed, so the box is in the center of the image. The problem is that the text is aligned left and I need it in the center. enter image description here

lStoilov
  • 1,256
  • 3
  • 14
  • 30
  • 1
    Possible duplicate of [Aligning php Generated Image dynamic text in center](https://stackoverflow.com/questions/14517094/aligning-php-generated-image-dynamic-text-in-center) – YTZ Jun 23 '19 at 18:24
  • Not really my problem... I need to align the text and not aligning the box in which the text is placed. I have already centered my box in the center of the image, the p[roblem is that the text within the box is aligned left and I need it to be centered as well. – lStoilov Jun 23 '19 at 18:35

0 Answers0