需求:根据输入的名字,自动计算名字字符的长度,来生成相应的签名png图片
难点: 自动计算输入文本的长度
public static function generateSignImage($sign_name){
if(empty($sign_name)){
return ['status' => false];
}
$height = 95;
$ttfPath = __DIR__.'/yizhiqingshu.ttf';
$w = static ::charwidth(56,0,$ttfPath,$sign_name);
$width = $w + 80 + 80;
$image = imagecreatetruecolor($width, $height);
//2.上色
$color=imagecolorallocate($image,255,255,255);
//3.设置透明
imagecolortransparent($image,$color);
imagefill($image,0,0,$color);
$text_color = imagecolorallocate($image, 26, 26, 26);
imagettftext($image, 56, 0, 80 , 76, $text_color, $ttfPath, $sign_name);
ob_start(); //启用输出缓冲
imagepng($image); //输出图像
$imagebin=ob_get_contents(); //将缓冲的数据存入变量
ob_end_clean(); //结束并清空输出缓存
imagedestroy($image);
$res = UploadFromServerHelper::uploadImageFromStream($imagebin);
//var_dump($res);
return $res;
}
static function charwidth($fontsize,$fontangle,$ttfpath,$char){
$box = imagettfbbox($fontsize,$fontangle,$ttfpath,$char);
$width = abs(max($box[2], $box[4]) - min($box[0], $box[6]));
return $width;
}