创建图像框,其高度取决于其包含的文本


PHP: Create Image Box whose Height Depends on its Contained Text

我试图使用PHP创建一个透明文本框与max的图像。2行文字。框的宽度固定为90px;高度取决于所包含的文本(同样,文本可能占用1到2行):示例。

我认为最具挑战性的部分是如何"自动"设置框的高度取决于文本长度。也就是说,脚本应该足够智能:

  1. 如果文本比宽度长,则换行(到第二行)。
  2. 调整框的高度,因为现在有两条线

假设文本总是适合一行和一个方框,脚本可以非常简单:

<?php
$im = imagecreatetruecolor(90, 22);
$white = imagecolorallocate($im, 255, 255, 255);
$blue = imagecolorallocate($im, 92, 149, 167);
// Set the background to be blue
imagefilledrectangle($im, 0, 0, 90, 22, $blue);
// Path to our font file
$font = './Arial.ttf';
imagefttext($im, 10, 0, 5, 15, $white, $font, "Barton Hotel");
// Output to browser
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
?>

使用imagettfbox获取文本的边界框,并使用该信息实际生成该框。

我有这个函数来生成word image:

function generate_words($word)
{
    $fontSize = 10;
    $fontFile = dirname( __FILE__ ) . '/fonts/verdana.ttf';
    $boundingBox = imagettfbbox($fontSize, 0, $fontFile, $word);
    $imageWord = imagecreate(abs($boundingBox[2]) + abs($boundingBox[0]), abs($boundingBox[7]) + abs($boundingBox[1]));
    $background = imagecolorallocate($imageWord, 255, 255, 255);
    $black = imagecolorallocate($imageWord, 0, 0, 0);
    imagettftext($imageWord, $fontSize, 0, 0, abs($boundingBox[5]), $black, $fontFile, $word);
    //print_r( $boundingBox );
    return $imageWord;    
}

像这样使用:

$imageWord = generate_words( "my text" );
$imageWordWidth = imagesx($imageWord);
$imageWordHeight = imagesy($imageWord);

最后,将生成的文本图像资源合并为基础图像或背景图像:

imagecopymerge($baseImage, $imageWord, $wordXLocationRelativeToBase, $wordYLocationRelativeToBase, 0, 0, $imageWordWidth, $imageWordHeight, 100);