Динамически писать текст поверх изображения и центрировать текст - PullRequest
0 голосов
/ 23 июня 2019

У меня есть скрипт, который пишет текст поверх изображения.Работает нормально, но текст выровнен по левому краю.

Я пытаюсь центрировать текст по горизонтали, но не уверен, как мне это сделать.

Вот кодчто у меня есть на данный момент

//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);

Любые идеи о том, как я могу отцентрировать текст?

Я уже центрировал поле, в котором находится текст, поэтому поле находится вцентр изображения.Проблема в том, что текст выровнен по левому краю, и мне нужно в центре.enter image description here

...