[英]Resize image size according to size of text
下面的PHP代碼生成文本作為動態創建的圖像,我怎樣才能使圖像只與文本一樣大? 謝謝。
<?php
header('Content-Type: image/jpeg');
$text='Test';
$img = imageCreate(200,200);
imagecolorallocate($img, 255, 255, 255);
$textColor = imagecolorallocate($img, 0, 0, 0);
imagefttext($img, 15, 0, 0, 55, $textColor, 'bgtbt.ttf', $text);
imagejpeg($img);
imagedestroy($img);
?>
更新1:我在這里找到了原始海報示例的答案 - 在PHP中用文本創建IMage - 如何制作多行?
更新2:Martin Geisler的版本也很好用
使用TrueType字體時,使用imageftbbox
函數獲取字體字符串排版的邊界框。 邊界框給出了從基點到文本占據的矩形中的四個角的偏移量。 因此,如果您將邊界框存儲在$bb
並使用imagefttext
將文本放在($x, $y)
,那么角將具有以下坐標:
($x + $bb[6], $y + $bb[7]) ($x + $bb[4], $y + $bb[5])
+-------+
| Hello |
+-------+
($x + $bb[0], $y + $bb[1]) ($x + $bb[2], $y + $bb[3])
這告訴我們,我們想要的圖像寬度為($x + $bb[2]) - ($x + $bb[6]) = $bb[2] - $bb[6]
,同樣地,圖像高度為$bb[3] - $bb[7]
。 然后,文本應該在該圖片中的坐標(-$bb[6], -$bb[7])
處呈現,因為我們希望
(0, 0) = ($x + $bb[6], $y + $bb[7]) ==> $x = -$bb[6] and $y = -$bb[7]
您可以使用此代碼進行試用。 把它放到一個名為img.php
的文件中並瀏覽到img.php?q=Hello
測試:
<?php
header("Content-type: image/png");
$q = $_REQUEST['q'];
$font = "Impact.ttf";
$size = 30;
$bbox = imageftbbox($size, 0, $font, $q);
$width = $bbox[2] - $bbox[6];
$height = $bbox[3] - $bbox[7];
$im = imagecreatetruecolor($width, $height);
$green = imagecolorallocate($im, 60, 240, 60);
imagefttext($im, $size, 0, -$bbox[6], -$bbox[7], $green, $font, $q);
imagepng($im);
imagedestroy($im);
?>
如果您使用位圖字體,請查看imagefontwidth
和imagefontheight
函數。
@Martin Geisler的答案幾乎是正確的,但我無法讓我的文字完全適合圖像。 我嘗試了這個,它完美無缺!
從PHP手冊的用戶貢獻說明 :
$text = "<?php echo \"hello, world\"; ?>";
$font = "./arial.ttf";
$size = "60";
$bbox = imagettfbbox($size, 0, $font, $text);
$width = abs($bbox[2] - $bbox[0]);
$height = abs($bbox[7] - $bbox[1]);
$image = imagecreatetruecolor($width, $height);
$bgcolor = imagecolorallocate($image, 255, 255, 255);
$color = imagecolorallocate($image, 0, 0, 0);
$x = $bbox[0] + ($width / 2) - ($bbox[4] / 2);
$y = $bbox[1] + ($height / 2) - ($bbox[5] / 2);
imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $bgcolor);
imagettftext($image, $size, 0, $x, $y, $color, $font, $text);
$last_pixel= imagecolorat($image, 0, 0);
for ($j = 0; $j < $height; $j++)
{
for ($i = 0; $i < $width; $i++)
{
if (isset($blank_left) && $i >= $blank_left)
{
break;
}
if (imagecolorat($image, $i, $j) !== $last_pixel)
{
if (!isset($blank_top))
{
$blank_top = $j;
}
$blank_left = $i;
break;
}
$last_pixel = imagecolorat($image, $i, $j);
}
}
$x -= $blank_left;
$y -= $blank_top;
imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $bgcolor);
imagettftext($image, $size, 0, $x, $y, $color, $font, $text);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.