」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用 PHP 為圖片添加浮水印?

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

發佈於2024-11-06
瀏覽:700

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() 釋放所使用的記憶體。

範例程式碼

以下是範例程式碼片段:

// 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);
版本聲明 本文轉載於:1729231338如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3