php - 在 PHP 中从文本创建图像 - 如何制作多行?

标签 php image-processing gd freetype

我有一个使用 PHP 从文本生成图像的脚本。它工作正常,除了我希望它生成多行文本以及不同的颜色。如何使用 PHP、GD 和 Freetype 完成?下面是我用来生成单行文本图像的代码。

$textval = 'This is some text to be an image';
$textcolor = '666666';


$font="arial.ttf";
$size = 9;
$padding= 1;
$bgcolor= "ffffff";

$transparent = 0;
$antialias = 0;

$fontfile = $fontpath.$font;

$box= imageftbbox( $size, 0, $fontfile, $textval, array());
$boxwidth= $box[4];
$boxheight= abs($box[3]) + abs($box[5]);
$width= $boxwidth + ($padding*2) + 1;
$height= $boxheight + ($padding) + 0;
$textx= $padding;
$texty= ($boxheight - abs($box[3])) + $padding;

// create the image
$png= imagecreate($width, $height);


$color = str_replace("#","",$bgcolor);
$red = hexdec(substr($bgcolor,0,2));
$green = hexdec(substr($bgcolor,2,2));
$blue = hexdec(substr($bgcolor,4,2));
$bg = imagecolorallocate($png, $red, $green, $blue);

$color = str_replace("#","",$textcolor);
$red = hexdec(substr($textcolor,0,2));
$green = hexdec(substr($textcolor,2,2));
$blue = hexdec(substr($textcolor,4,2));
$tx = imagecolorallocate($png, $red, $green, $blue);



imagettftext( $png, $size, 0, $textx, $texty, $tx, $fontfile, $textval );

header("content-type: image/jpeg");
imagejpeg($png);
imagedestroy($png);
exit;

最佳答案

添加此函数以在文本进入您的函数之前对其进行换行。

function wrap($fontSize, $angle, $fontFace, $string, $width){

    $ret = "";

    $arr = explode(' ', $string);

    foreach ( $arr as $word ){

        $teststring = $ret.' '.$word;
        $testbox = imagettfbbox($fontSize, $angle, $fontFace, $teststring);
        if ( $testbox[2] > $width ){
            $ret.=($ret==""?"":"\n").$word;
        } else {
            $ret.=($ret==""?"":' ').$word;
        }
    }

    return $ret;
}

来源:http://www.php.net/imagettftext

关于php - 在 PHP 中从文本创建图像 - 如何制作多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1097583/

相关文章:

PHP 表单通过 URL 传递值

python - 如何将 reshape /展平的图像附加到Python列表而不消耗太多内存?

php - CSS:将字体设置为一定大小,以便文本占据整个容器

php - 在数组中搜索匹配的字符串

javascript - PHP/Javascript 中实时更新时间

javascript - 在客户端从 base64 图像字符串(使用 javascript 或 jquery)中提取 exif

php - 从任何文件类型的 URL 创建图像

ubuntu - 如何在 xampp Ubuntu 18.04 中安装/启用 GD?

javascript - 修改PHP使用JS/JQuery与MySQL通信

java - 改善直方图