我为php中的图像创建代码并保存到png / jpeg。 但问题是有时候文本太长而且没有覆盖整个区域。它将开箱即用,文本丢失。 代码就像这样
<?php
$im = imagecreatetruecolor(400, 30);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);
$text = 'Testing...';
$font = 'arial.ttf';
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
imagejpeg($im,'name.jpg');
imagedestroy($im);
?>
当我添加长文本时,这个代码可以正常工作。它还有其他解决办法将文本自动调整到框中吗?
答案 0 :(得分:0)
好的,我做了一个小功能(尚未测试)
function getTextFactor($font, $text, $size, $angle, $width, $height)
{
//if the size are zero don't execute any further, it's not necessary
if($width == 0 || $height == 0) throw new ArgumentException("$width or $height could not be zero!");
//get the text size
$box = imagettfbbox($size, $angle, $font, $text);
$minX = min(array($box[0],$box[2],$box[4],$box[6]));
$maxX = max(array($box[0],$box[2],$box[4],$box[6]));
$minY = min(array($box[1],$box[3],$box[5],$box[7]));
$maxY = max(array($box[1],$box[3],$box[5],$box[7]));
$factorX = 1;
if($tmpWdith = ($maxX - $minX) > $width)
{
$factorX = $tmpWidth / $width;
}
$factorY = 1;
if($tmpHeight = ($maxY - $minY) > $height)
{
$factorY = $tmpHeight / $height;
}
return min(array($factorX, $factorY));
}
您将获得调整图像中字体大小的因素。
您可以在脚本中使用以下内容:
$width = 400;
$height = 30;
$textSize = 20;
$textAngle = 0;
$text = 'Testing...';
$font = 'arial.ttf';
$im = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, $width-1, $height-1, $white); //why exactly do you subtract 1?
$factor = getTextFactor($font, $text, $textSize, $textAngle, $width, $height);
imagettftext($im, $textSize*$factor, $textAngle, 10, 20, $black, $font, $text);
imagejpeg($im, 'name.jpg');
imagedestroy($im);
请注意,目前上述因素功能并未使用文本的填充或边距。
如果您想要宽度,请使用以下函数:
function getTextBox($font, $text, $size, $angle)
{
$box = imagettfbbox($size, $angle, $font, $text);
$minX = min(array($box[0],$box[2],$box[4],$box[6]));
$maxX = max(array($box[0],$box[2],$box[4],$box[6]));
$minY = min(array($box[1],$box[3],$box[5],$box[7]));
$maxY = max(array($box[1],$box[3],$box[5],$box[7]));
return array("width" => abs($maxX - $minX), "height" => abs($maxY - $minY));
}
然后用你得到的尺寸创建图像。