请先确认是否已安装 GD 库(含FreeType)
步骤一:计算文字的长与宽
$size=12; //字体大小
$font= "abc.ttf"; //字体类型
$box = imagettfbbox($size , 0, $font, $text); // 取得字体的文本的范围
$min_x = min( array($box[0], $box[2], $box[4], $box[6]) );
$max_x = max( array($box[0], $box[2], $box[4], $box[6]) );
$min_y = min( array($box[1], $box[3], $box[5], $box[7]) );
$max_y = max( array($box[1], $box[3], $box[5], $box[7]) );
$width = ( $max_x - $min_x ); // 宽度
$height = ( $max_y - $min_y ); // 高度
步骤二:生成图片
// 此处的长与宽在第一步生成
$img=imagecreate($width,$height); //创建一个空白图片
imagecolorallocate($img,0xff,0xff,0xff);//设置图片背景颜色,这里背景颜色为#ffffff,也就是白色
$black=imagecolorallocate($img,0x00,0x00,0x00); //设置字体颜色,这里为#000000,也就是黑色
imagettftext($img,$size,0,0,16,$black,$font,$text);//将ttf文字写到图片中
header('Content-Type: image/png'); //发送头信息
$img_path = $filePath . "/temp_files/".date('YmdHis').'.png';// 图片路径/imgName.png
imagepng($img, $img_path); // 将生成的图片保存到图片路径
imagedestroy($img);
//unlink($img_path); // 临时用文件可删除
解决宽度过长时展示问题
- 纯英文可使用
chunk_split
- 中英文可使用下面的方法
/**
* @param [string] $string [生成的文字]
* @param integer $len [拆分的长度]
*/
public static function mbStrSplit($string, $len=1) {
$start = 0;
$strlen = mb_strlen($string);
while ($strlen) {
$str[] = mb_substr($string,$start,$len,"utf8");
$string = mb_substr($string, $len, $strlen,"utf8");
$strlen = mb_strlen($string);
}
return implode("\n", $str);
}