PHP GD - Align text center-horizontally and decrease font size to keep it inside the image

前端 未结 2 1082
长情又很酷
长情又很酷 2021-02-10 01:58

Hope you are doing great.

I’m still a newbie with php so after making some reading and while checking some posts here I was able to put some text over an image with the

2条回答
  •  我寻月下人不归
    2021-02-10 02:34

    You need the width of the image and the width of the text to relate both.

    // get image dimensions
    list($img_width, $img_height,,) = getimagesize("fabian.jpg");
    
    // find font-size for $txt_width = 80% of $img_width...
    $font_size = 1; 
    $txt_max_width = intval(0.8 * $img_width);    
    
    do {        
        $font_size++;
        $p = imagettfbbox($font_size, 0, $font_path, $text);
        $txt_width = $p[2] - $p[0];
        // $txt_height=$p[1]-$p[7]; // just in case you need it
    } while ($txt_width <= $txt_max_width);
    
    // now center the text
    $y = $img_height * 0.9; // baseline of text at 90% of $img_height
    $x = ($img_width - $txt_width) / 2;
    
    imagettftext($jpg_image, $font_size, 0, $x, $y, $white, $font_path, $text);
    

提交回复
热议问题