open($backdropImage, $filePath); // 获取背景图宽高 $size = getimagesize($filePath); //获取文字类型路劲 $fontPath = Grafika::fontsDir().DS.'st-heiti-light.ttc'; //获取文字数量 $fontNum = mb_strlen($waterText); // 3.创建文字图片 //判断是否需要添加水印 if ($type) { //获取斜边长度 $hypo = hypot($size[0], $size[1]); // 判断文字图片开始的位置 $fontSize = intval($hypo) / $fontNum * 0.5; // 获取文字大小宽高 $fontSizeArr = $this->get_text_box($waterText, $fontSize, $fontPath); $fontX = intval(($size[0] * (($hypo - $fontSizeArr[0]) / 2)) / $hypo); $fontY = $size[1] - intval(($size[1] * (($hypo - $fontSizeArr[0]) / 2)) / $hypo); //计算倾斜角度 $angle = intval(atan($size[1] / $size[0]) * 180 / pi()); $image = imagecreatetruecolor($size[0], $size[1]); } else { // 判断文字图片开始的位置 $fontSize = $size[0] / $fontNum; // 获取文字大小宽高 $fontSizeArr = $this->get_text_box($waterText, $fontSize, $fontPath); $fontX = 0; $fontY = 0; $angle = 0; $image = imagecreatetruecolor($fontSizeArr[0], $fontSizeArr[1]); } imagesavealpha($image, true); // 设置透明度 $frontImageSource = imagecolorallocatealpha($image, 0, 0, 0, 127); imagefill($image, 0, 0, $frontImageSource); //生成文字透明背景板 $fontImage = new \Grafika\Gd\Image($image, '', imagesx($image), imagesy($image), ImageType::PNG); //设置文字颜色 $Color = new Color('#CCCCCC'); $editor->text($fontImage, $waterText, $fontSize, $fontX, $fontY, $Color, $fontPath, $angle); if($waterText2){ $editor->text($fontImage, $waterText2, $fontSize, $fontX + $fontSize, $fontY + $fontSize, $Color, $fontPath, $angle); } //合并图片 $editor->blend($backdropImage, $fontImage, 'overlay', 1, 'center'); // 保存图片 $editor->save($backdropImage, $filePath); return true; } /** * [get_text_box] * 根据文字获取宽高 * * @Author: Yeshihao * @DateTime: 2023/11/14 10:04 * @param $text * @param $size * @param $font * @return array */ private function get_text_box($text, $size, $font) { $point = imagettfbbox($size, 0, $font, $text); $width = $point[4] - $point[6]; $height = $point[1] - $point[7]; return [$width, $height]; } }