获取文本的框大小并创建图像文本


Getting boxsize of text and create an image text

我想从textearea为时事通讯创建一个文本图像。所以,它会有不止一行。我在考虑使用imagettfbbox来计算(所有行的)总宽度和高度,然后使用imagettftext在图像中写入。问题是,我注意到字体大小越大,在文本中添加"imagettftext"的填充就越多。imagettfbbox没有告诉我关于填充的任何信息。返回的数组值[0]和[1]都是ALLWAYS=-1。

谢谢!

您可以使用GD或ImageMagick来完成此操作,我将发布一个使用GD.的基本示例

<?php
// Set the content-type
header('Content-Type: image/png');
// Create the image
$im = imagecreatetruecolor(400, 30);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);
// The text to draw
$text = 'A simple text string';
// Replace path by your own font path
$font = 'tahoma.ttf';
// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>

现在,为了格式化这个字符串,您可以使用strlen()返回单个字符串的长度,并根据需要将其传播到您的函数。对于更符合流的方法,请考虑使用ImageMagick,因为它支持TextAlignment等。

<?php
define("LEFT", 1);
define("CENTER", 2);
define("RIGHT", 3);
$w = 400;
$h = 200;
$gradient = new Imagick();
$gradient->newPseudoImage($w, $h, "gradient:red-black");
$draw = new ImagickDraw();
$draw->setFontSize(12);
$draw->setFillColor(new ImagickPixel("#ffffff"));
$draw->setTextAlignment(LEFT);
$draw->annotation(150, 30, "Hello World1!");
$draw->setTextAlignment(CENTER);
$draw->annotation(150, 50, "Hello World2!");
$draw->setTextAlignment(RIGHT);
$draw->annotation(150, 70, "Hello World3!");
$draw->setFillColor(new ImagickPixel("#0000aa"));
$x1 = 150;
$x2 = 150;
$y1 = 0;
$y2 = 200;
$draw->rectangle($x1, $y1, $x2, $y2);
$gradient->drawImage($draw);
$gradient->setImageFormat("png");
header("Content-Type: image/png");
echo $gradient;
?>

我希望这对你有帮助。我可以详细说明你可能提出的任何问题。