2016-01-20 73 views
0

我想創建具有給定文本的確切尺寸的圖像,並將該文本放置到該圖像上。我從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); 

?> 

我從這個得到的是Cutted edges

我要的是:Text fitting inside the image

計算的寬度和高度似乎是正確的;但是,X/Y位置($ offset_x和$ offset_y)不是。

我該如何動態設置$ offset_x和$ offset_y,以便文本完全適合不同字體,大小和樣式的圖像?

回答

0

回答我自己的問題。 這是一個很長時間的PHP錯誤。見https://bugs.php.net/bug.php?id=52756 並且仍然存在於PHP 7.0.1

了錯誤的測試腳本可以在這裏找到:http://stuff.mindplay.dk/temp/metrics/test.php

爲了讓我的東西的工作,我用了一個想法從評論php.net http://php.net/manual/de/function.imagettfbbox.php#97357

這個想法是將文本繪製到更大的畫布上,並在每個像素上進行迭代以找到每側(頂部,右側,底部,左側)的確切位置。這很慢,特別是在較大的圖像上,但它適用於我。

如果任何人有另一個更快或更優雅的想法,我非常感興趣,閱讀它。

+0

只是爲了記錄。在最新的PHP版本5.6.29和PHP 7.1.0中解決了這個問題,並且解決方法可能不再需要。 – kirschkern

0

這裏是在github上一個library,以幫助您滿足您的文本完全

示例代碼

$text_measure = new TextMeasure($text, $font_path, $size); 
$measure = $text_measure->measureText(); 

用什麼量器量數組是這樣的:

$gd_image = imagecreatetruecolor($measure['width'], $measure['height']); 
imagettftext($gd_image, $size, 0, $measure['x'], $measure['y'], $red, $font_path, $text); 

前瞻: enter image description here