/**
* 给图片添加文字水印 可控制字体颜色透明度,默认是居中
* @param string $imagePath 图片地址
* @param string $outputPath 新图片地址 默认使用$imgurl
* @param string $textArray 水印文字
* @param int $fontSize 字体大小
* @param string $fontPath 字体文件路径
* @param int $fontSize 字体大小
* @return boolean
*/
function addTextWatermark($imagePath, $outputPath, $textArray, $fontPath = '', $fontSize = 14)
{
$fontPath = $fontPath ?: dirname(dirname(dirname(dirname(__FILE__)))) . "/images/fonts/msyh.ttc";
// 获取图片信息
$imageInfo = getimagesize($imagePath);
$imageWidth = $imageInfo[0];
$imageHeight = $imageInfo[1];
// 创建图片资源
$image = imagecreatefromstring(file_get_contents($imagePath));
// 设置水印文字颜色和字体大小
$textColor = imagecolorallocatealpha($image, 255, 255, 255, 60); // 白色,透明度为100
$textColorTitle = imagecolorallocate($image, 255, 255, 255); // 白色
$textSpacing = 10; // 间隔值
$textName = $textArray['name'];
$textTitle = $textArray['title'];
// 计算文字水印的宽度和高度
$textBoundingBoxName = imagettfbbox($fontSize, 0, $fontPath, $textName);
$textWidthName = $textBoundingBoxName[2] - $textBoundingBoxName[0];
$textHeightName = $textBoundingBoxName[1] - $textBoundingBoxName[7];
$textBoundingBoxTitle = imagettfbbox($fontSize, 0, $fontPath, $textTitle);
$textWidthTitle = $textBoundingBoxTitle[2] - $textBoundingBoxTitle[0];
$textHeightTitle = $textBoundingBoxTitle[1] - $textBoundingBoxTitle[7];
// 计算水印文字的位置
$xName = ($imageWidth - $textWidthName - $textWidthTitle - $textSpacing) / 2;
$yName = ($imageHeight + $textHeightName) / 2;
$xTitle = $xName + $textWidthName + $textSpacing;
$yTitle = ($imageHeight + $textHeightTitle) / 2;
// 添加水印文字
imagettftext($image, $fontSize, 0, $xName, $yName, $textColor, $fontPath, $textName);
imagettftext($image, $fontSize, 0, $xTitle, $yTitle, $textColorTitle, $fontPath, $textTitle);
// 保存图片
imagepng($image, $outputPath);
// 释放图片资源
imagedestroy($image);
}
$imagePath = '../../image/up_image/20231214/231214551024943405.jpg';
$outputPath = '../../image/up_image/20231213/' . imgSuiYin('231214551024943405.jpg');
$textArray = array('name' => '@急急急', 'title' => '爱看');
addTextWatermark($imagePath, $outputPath, $textArray);