dpo60833 2019-06-23 17:57
浏览 93

动态地在文本上写入文本并使文本居中

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 .= "
".$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

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 请教一下各位,为什么我这个没有实现模拟点击
    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 保护模式-系统加载-段寄存器
    • ¥15 电脑桌面设定一个区域禁止鼠标操作