需求:根據輸入的名字,自動計算名字字符的長度,來生成相應的簽名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;
}