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

DDD
發布: 2024-10-18 14:03:30
原創
219 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!