我想創建具有給定文本的確切尺寸的圖像,並將該文本放置到該圖像上。我從imagettfbbox獲取的位置值似乎並不準確,特別是對於斜體字體樣式。這導致一些字符在右邊被切斷。如何通過imagettfbbox獲取確切位置?
這裏是我的代碼:
<?php
Header("Content-type: image/png");
$font = 'fonts/ArialItalic.ttf';
$text = "SOB";
$size = 48;
$bounds = imagettfbbox($size, 0, $font, $text);
$width = abs($bounds[4]-$bounds[6]);
$height = abs($bounds[7]-$bounds[1]);
$offset_y = $height;
$offset_x = $bounds[0];
$image = imagecreate($width,$height);
$background = ImageColorAllocate($image, 0, 0, 0);
$foreground = ImageColorAllocate($image, 255, 255, 255);
ImageTTFText($image, $size, 0, $offset_x, $offset_y, -$foreground, $font, $text);
imagePNG($image);
imagedestroy($image);
?>
計算的寬度和高度似乎是正確的;但是,X/Y位置($ offset_x和$ offset_y)不是。
我該如何動態設置$ offset_x和$ offset_y,以便文本完全適合不同字體,大小和樣式的圖像?
只是爲了記錄。在最新的PHP版本5.6.29和PHP 7.1.0中解決了這個問題,並且解決方法可能不再需要。 – kirschkern