-->

PHP imagettftext return bounding box differs from

2019-07-19 05:17发布

问题:

I'm using imagettftext to render a PNG file. A call to imagettftext() returns the bounding box that the text was rendered in, but on closer inspection, the text is being rendered slightly outside of it's own bounding box! The bounding box is correct (I inspected the pixel coords of the image), but the text location is incorrect, it outputs this, where the box is the returned bounding box after rendering the text:

My code is:

// helper function for geting textbox bounds
function bounds($text,$fontFile,$fontSize,$fontAngle) { 
    $rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text); 
    $minX = min(array($rect[0],$rect[2],$rect[4],$rect[6])); 
    $maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6])); 
    $minY = min(array($rect[1],$rect[3],$rect[5],$rect[7])); 
    $maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7])); 

    return array( 
        "left"   => abs($minX) - 1, 
        "top"    => abs($minY) - 1, 
        "width"  => $maxX - $minX, 
        "height" => $maxY - $minY, 
        "box"    => $rect 
    ); 
}

$canvas = @imagecreate(640, 680)
    or die('Cannot Initialize new GD image stream');

$title_color = imagecolorallocate($canvas, 153, 153, 153);
$content_color = imagecolorallocate($canvas, 51, 51, 51);

$content_bounds = bounds("12", "Helvetica_Reg.ttf", 75, 0);
$test = imagettftext($canvas, 75, 0, 30, 200, $content_color, "Helvetica_Reg.ttf", "12");
imagerectangle($canvas, $test[0], $test[1], $test[4], $test[5], $title_color);

回答1:

maybe is a problem with the font, i test your code with another one, and i got