PHP 在图片中写入文字,并根据文字长度自动换行
将文字写如到PNG图片中,并根据图片的长度,限制文字的行宽,实现自动换行
在 校牌、海报、宣传册 等合成上非常实用
/**
* @param $title 需要加入的文字
* @param $original_image PNG透明图片
* @return string
*/
public function addText($title,$original_image){
// $title = '任意文字皆可生成,文字始终保持在中间,任意文字皆可生成,文字始终保持在中间';
$font=Config::get('custom.wmzt');//字体文件引入
$w = 800;
$h = 100;
$h2 = 600;
$img = imagecreatetruecolor($w,100);//建立一张图片,设置宽高
$tbg = imagecolorallocatealpha($img,0,0,0,127);//设置图片透明背景
$color = imagecolorallocate($img,150,150,150); //设置字体颜色
$size=20;//字体大小
imagealphablending($img, false);//显示透明背景
imagefill($img,0,0,$tbg);//填充背景
//拆分文字长度
$strArr = [];
$strlen = mb_strlen($title,'utf-8');
if($strlen>30){
$strArr = self::mbStrSplit($title,30);
}
if($strlen>30){
foreach ($strArr as $k=>$v){
$the_box = self::calculateTextBox($v, $font, $size, 0);
if($k==0){
imagefttext($img,$size,0,$the_box["left"] + ($w/ 2) - ($the_box["width"] / 2),$the_box["top"] + ($h/ 6) - ($the_box["height"] / 2),$color,$font,$v);
}elseif ($k==1){
imagefttext($img,$size,0,$the_box["left"] + ($w/ 2) - ($the_box["width"] / 2),$the_box["top"] + ($h/ 2) - ($the_box["height"] / 2),$color,$font,$v);
}
}
}else{
$the_box = self::calculateTextBox($title, $font, $size, 0);
imagefttext($img,$size,0,$the_box["left"] + ($w/ 2) - ($the_box["width"] / 2),$the_box["top"] + ($h/ 2) - ($the_box["height"] / 2),$color,$font,$title);
}
imagesavealpha($img,true);
$_path = '/www/wwwroot/web/public/aaa';
if(!file_exists($_path))
{
mkdir($_path, 0700);
}
$saveUrl = $_path.time().'.png';
imagepng($img,$saveUrl);
$a = imagecreatefrompng($original_image);
$b = imagecreatefrompng($saveUrl);
$image = imagecreatetruecolor($width, $height);//建立个原图大小的画板
$bg = imagecolorallocatealpha($image , 0 , 0 , 0 , 127);
imagefill($image , 0 , 0 , $bg);
imagesavealpha($image, true);
imagecopy($image, $a, 0, 0, 0, 0, $w, $h2);
imagecopy($image, $b, 0, 270, 0, 0, $w, $h);
$filename =$_path.(time()+1).'.png';
@unlink($saveUrl);
header('Content-type: image/png');
imagepng($image);
}
//计算文字所占宽度
private function calculateTextBox($text,$fontFile,$fontSize,$fontAngle) {
$rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text);
$minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
$maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
$minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
$maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7]));
return array(
"left" => abs($minX) - 1,
"top" => abs($minY) - 1,
"width" => $maxX - $minX,
"height" => $maxY - $minY,
"box" => $rect
);
}
//分割字符串为数组模式
private function mbStrSplit ($string, $len=1) {
$start = 0;
$strlen = mb_strlen($string);
while ($strlen) {
$array[] = mb_substr($string,$start,$len,"utf8");
$string = mb_substr($string, $len, $strlen,"utf8");
$strlen = mb_strlen($string);
}
return $array;
}