愤怒的小菜
小菜的成长博客
php Imagick写文字图片并自动换行
效果:
代码:
function echoImgAction(){
$text = " 战争网游巨作《坦克世界》领土争夺战将在近日重新开启新的征程。全新地图,多样玩法,更大参战范围;普通玩家、资深高玩以及专业电竞人士都会重装上阵。今天,小编带领大家回忆领土战曾经的吸金之地,全方位感受《坦克世界》领土争夺战带来的全民参战的宏伟壮丽。";
$top = 10;
$left = 5;
$eol = PHP_EOL;
$fontsize = 12;
$fontfile = 'msyh.ttf';
$text = $this->autowrap($fontsize,$fontfile,$text,500);
$canvas = new Imagick();
$canvas->newImage(500, 400, 'white', 'jpg');
$canvas->setImageFormat('png');
$draw = new ImagickDraw();
$draw->setFontSize($fontsize);//设置字体大小
$draw->setFillColor('#7D7B7B');//设置字体颜色
$draw->setFont($fontfile);
$canvas->annotateImage($draw, $left, ($fontsize+2)+$top, 0, $text);
header("Content-Type: image/png");
echo $canvas;
return false;
}
函数:
/**
* 返回一个字符的数组
* @param $str 文字
* @param $charset 字符编码
*/
function chararray($str,$charset="utf-8"){
$re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
$re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
$re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
$re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
preg_match_all($re[$charset], $str, $match);
return $match;
}
/**
* 返回一个字符串在图片中所占的宽度
* @param $fontsize 字体大小
* @param $fontangle 角度
* @param $ttfpath 字体文件
* @param $char 字符
*/
function charwidth($fontsize,$fontangle,$ttfpath,$char){
$box = @imagettfbbox($fontsize,$fontangle,$ttfpath,$char);
$width = max($box[2], $box[4]) - min($box[0], $box[6]);
return $width;
}
/**
* 根据预设宽度让文字自动换行
* @param $fontsize 字体大小
* @param $ttfpath 字体名称
* @param $str 字符串
* @param $width 预设宽度
* @param $fontangle 角度
* @param $charset 编码
*/
function autowrap($fontsize,$ttfpath,$str,$width,$fontangle=0,$charset='utf-8'){
$_string = "";
$_width = 0;
$temp = $this->chararray($str);
foreach ($temp[0] as $k=>$v){
$w = $this->charwidth($fontsize,$fontangle,$ttfpath,$v);
$_width += intval($w);
if (($_width > $width) && ($v !== "")){
$_string .= PHP_EOL;
$_width = 0;
}
$_string .= $v;
$w = 0;
}
//$_string = mb_convert_encoding($_string, "html-entities","utf-8" );
return $_string;
}