在PHP中用文本创建IMage - 如何创建多行? [英] Creating IMage from Text in PHP - how can I make multiline?

查看:212
本文介绍了在PHP中用文本创建IMage - 如何创建多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a script that generates images from text using PHP. It's working fine except that I would like it to generate multiline text as well with differing colors. How can it be done using PHP, GD and Freetype? Below is the code I use to generate single line text images.

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


推荐答案

添加此函数以在文本进入之前包装文本你的功能。

Add this function to wrap the text before it goes into your function.

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中用文本创建IMage - 如何创建多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆