要在PHP中添加水印文字背景,可以使用GD库来实现。以下是一个简单的示例代码:
<?php
// 源图片路径
$sourceImagePath = 'path/to/source/image.jpg';
// 创建图像资源
$sourceImage = imagecreatefromjpeg($sourceImagePath);
// 设置水印文字颜色和背景颜色
$watermarkColor = imagecolorallocate($sourceImage, 255, 255, 255); // 白色
$backgroundColor = imagecolorallocatealpha($sourceImage, 0, 0, 0, 50); // 半透明黑色背景
// 设置水印文字和字体
$watermarkText = 'Watermark Text';
$fontPath = 'path/to/font.ttf'; // 字体文件路径
// 设置水印文字的位置
$watermarkX = 10; // 水印文字的X坐标
$watermarkY = 10; // 水印文字的Y坐标
// 添加水印文字背景
$textBoundingBox = imagettfbbox(12, 0, $fontPath, $watermarkText);
$textWidth = $textBoundingBox[2] - $textBoundingBox[0];
$textHeight = $textBoundingBox[1] - $textBoundingBox[7];
imagefilledrectangle($sourceImage, $watermarkX, $watermarkY, $watermarkX + $textWidth, $watermarkY + $textHeight, $backgroundColor);
// 添加水印文字
imagettftext($sourceImage, 12, 0, $watermarkX, $watermarkY, $watermarkColor, $fontPath, $watermarkText);
// 输出图像
header('Content-Type: image/jpeg');
imagejpeg($sourceImage);
// 释放资源
imagedestroy($sourceImage);
?>
在上面的示例中,首先通过imagecreatefromjpeg()函数创建了源图片的图像资源。然后使用imagecolorallocate()函数设置了水印文字的颜色,使用imagecolorallocatealpha()函数设置了水印文字背景的颜色。接下来,使用imagettfbbox()函数获取水印文字的边界框大小,然后使用imagefilledrectangle()函数在指定位置绘制了水印文字的背景。最后,使用imagettftext()函数在指定位置添加了水印文字。最后,使用imagejpeg()函数将处理后的图像输出到浏览器,并通过imagedestroy()函数释放了图像资源。
请注意,上述示例中的路径需要根据实际情况进行修改。此外,还可以根据需要调整水印文字的大小、字体、位置和颜色等参数。
上一篇:php反射器怎么使用
下一篇:php+根据数组元素排序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站