首页  >  文章  >  后端开发  >  如何使用 PHP 为图像添加水印?

如何使用 PHP 为图像添加水印?

DDD
DDD原创
2024-10-18 14:03:30219浏览

How Can I Add Watermarks to Images Using PHP?

使用 PHP 向图像添加水印

如果您正在开发允许用户上传图像的网站,则可能需要添加这些图像的水印,以防止未经授权的使用。添加水印可确保您的徽标或品牌在每个上传的图像上都可见。以下是如何在 PHP 中实现此目的:

使用 PHP 函数

PHP 手册提供了使用以下函数的综合示例:

  • imagecreatefrompng() - 以 PNG 格式加载水印图像
  • imagecreatefromjpeg() - 以 JPEG 格式加载要加水印的原始图像
  • imagecopy() - 将水印图像复制到原始图像上

定位水印

要有效定位水印,您可以使用 $marge_right 和 $marge_bottom 变量指定边距。这允许您控制水印与原始图像边缘之间的距离。

输出带水印的图像

添加水印后,您可以输出使用 header() 函数将带水印的图像设置为 PNG 内容类型。然后,使用 imagepng() 输出图像,使用 imagedestroy() 释放所使用的内存。

示例代码

以下是示例代码片段:

<code class="php">// Load the stamp and the photo to apply the watermark to
$stamp = imagecreatefrompng('stamp.png');
$im = imagecreatefromjpeg('photo.jpeg');

// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

// Copy the stamp image onto our photo using the margin offsets and the photo 
// width to calculate positioning of the stamp. 
imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));

// Output and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);</code>

以上是如何使用 PHP 为图像添加水印?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn