动态在图像上写文本并将文本居中

时间:2019-06-23 17:57:31

标签: php gd imagettftext

我有一个脚本,可以在图像上写文本。 效果很好,但是文本在左侧对齐。

我试图将文本水平居中,但不确定如何做到这一点。

这是我目前拥有的代码

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

0 个答案:

没有答案