【问题标题】:PHP: Create Image Box whose Height Depends on its Contained TextPHP:创建高度取决于其包含文本的图像框
【发布时间】:2011-12-21 19:08:34
【问题描述】:

我正在尝试使用 PHP 创建最大透明文本框的图像。 2行文字。框宽固定为90px;高度取决于包含的文本(同样,文本可能占据 1 到 2 行):example

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

  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);
?>

【问题讨论】:

    标签: php image image-processing


    【解决方案1】:

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

    我有这个功能来生成文字图像:

    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);
    

    【讨论】:

    猜你喜欢
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    相关资源
    最近更新 更多