PHP之添加文字水印,两端文字分别设置不同的样式,支持透明度

php 复制代码
/**
 * 给图片添加文字水印 可控制字体颜色透明度,默认是居中
 * @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);
}
php 复制代码
$imagePath = '../../image/up_image/20231214/231214551024943405.jpg';
$outputPath = '../../image/up_image/20231213/' . imgSuiYin('231214551024943405.jpg');
$textArray = array('name' => '@急急急', 'title' => '爱看');

addTextWatermark($imagePath, $outputPath, $textArray);
相关推荐
Fairy_sevenseven2 分钟前
【二十八】【QT开发应用】模拟WPS Tab
开发语言·qt·wps
蜡笔小新星10 分钟前
Python Kivy库学习路线
开发语言·网络·经验分享·python·学习
凯子坚持 c10 分钟前
C语言复习概要(三)
c语言·开发语言
无限大.22 分钟前
c语言200例 067
java·c语言·开发语言
余炜yw23 分钟前
【Java序列化器】Java 中常用序列化器的探索与实践
java·开发语言
篝火悟者25 分钟前
问题-python-运行报错-SyntaxError: Non-UTF-8 code starting with ‘\xd5‘ in file 汉字编码问题
开发语言·python
Death20027 分钟前
Qt 中的 QListWidget、QTreeWidget 和 QTableWidget:简化的数据展示控件
c语言·开发语言·c++·qt·c#
六点半88828 分钟前
【C++】速通涉及 “vector” 的经典OJ编程题
开发语言·c++·算法·青少年编程·推荐算法
惜.己29 分钟前
javaScript基础(8个案例+代码+效果图)
开发语言·前端·javascript·vscode·css3·html5
niu_sama32 分钟前
基于muduo库函数实现protobuf协议的通信
开发语言·qt