首頁 >後端開發 >php教程 >如何使用 PHP 為圖片添加浮水印?

如何使用 PHP 為圖片添加浮水印?

DDD
DDD原創
2024-10-18 14:03:30330瀏覽

How Can I Add Watermarks to Images Using PHP?

Add Watermarks to Images Using PHP

If you're working on a website that allows users to upload images, you may need to add a watermark to those images to protect them from unauthorized use. Adding a watermark ensures that your logo or branding is visible on every uploaded image. Here's how you can achieve this in PHP:

Using PHP Functions

The PHP manual provides a comprehensive example using the following functions:

  • imagecreatefrompng() - Loads the watermark image as a PNG
  • imagecreatefromjpeg() - Loads the original image to be watermarked as a JPEG
  • imagecopy() - Copies the watermark image onto the original image

Positioning the Watermark

To position the watermark effectively, you can specify the margins using the $marge_right and $marge_bottom variables. This allows you to control the distance between the watermark and the edges of the original image.

Outputting the Watermarked Image

Once the watermark has been added, you can output the watermarked image using the header() function to set the content type to PNG. Then, use imagepng() to output the image and imagedestroy() to free up the memory used.

Example Code

Here's an example code snippet:

<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