字体大小取决于图像大小

时间:2015-07-11 09:06:09

标签: php image imagick

对不起我的英语! 我在图像上使用imagick php和叠加文本来解决这个问题。 调整图像宽度时字体的大小很小。 这是两个图像宽度的示例,第一个是350px,第二个是1728px: http://i.stack.imgur.com/8kRo0.jpg http://i.stack.imgur.com/TedDO.jpg

$ f-> userFontSize 是用户选择在其图片上显示的字体大小。

if(trim($_GET['full']) != 'si'){
$width = 350;
$height = 350;
} else {
$width =    getWidth($root . $f->imagePathFull);
$height =     getHeight($root . $f->imagePathFull);
}
$image = new imagick();
$draw = new imagickDraw();
$pixel = new imagickPixel('white');
$image->newImage($width, $height, $pixel);
$image->readImage($root . $f->imagePathNormal); 
$image->resizeImage ( $width, $height,  imagick::FILTER_LANCZOS, 1, TRUE);
$fontPath = $root . '/assets/fonts/Mermaid.ttf';
$draw->setFillColor('black');
$draw->setFont($fontPath);
$draw->setFontSize(12 + $f->userFontSize);
$draw->setGravity(1);
$draw->setTextAntialias(true);
$draw->setFillOpacity(".55");
$image->annotateImage($draw, 5,0, 0, "text text text");
$image->setImageFormat("jpg");

header( "Content-Type: image/jpeg" );
echo $image->getImageBlob();
$image->clear();

当我打印分辨率为1728像素的图像时,文字非常小。如何根据图像大小增加字体大小? 谢谢! :)

1 个答案:

答案 0 :(得分:0)

我已经用这种方式解决了,我计算了文本在350px处占据图像的宽度百分比,并根据这个我计算了1728px(或另一个宽度)的百分比。我做了一些字体大小,直到我找到一个百分比的大小。我的解决方案的最终结果是不完美但可以接受的。这是代码:

$myCP = '40'; // increase o decrease font size.
for($i = 1; $i <= 500;$i++){
    $box = imagettfbbox($i, 0, $fontPath, "lorem ipsum");
    $lT = $box[2] - $box[0];
    $cP = round(($lT / $width) * 100,1);
    // $cP percentage of font width
    if($cP >= $myCP) { $newFontSize = $i; break; } else { continue; }
}