簡體   English   中英

即時生成PHP水印圖像

[英]PHP watermark images on the fly

背景

我已經通讀了許多站點,包括此站點,以尋求解決方案。 我有一個水印腳本,直到幾個月前它都可以正常工作。 我的托管服務提供商執行了例行更新並清除了我的腳本。 我對其進行了一次調整,此方法奏效了。 隨着時間的流逝,水印腳本似乎占用了大量系統資源,導致我的網站出現各種問題,包括圖像無法隨機加載等。目前,看來我可以在PHP 5.4或以上版本中運行該網站。和它下面。 如果有幫助,當前以5.4運行。

說明

該腳本旨在從特定位置查找大小不等的圖像文件,並與多個png圖像之一實時組合,而不會覆蓋原始圖像。

劇本

在過去一周中,我對腳本進行了重大修改,但性能略有改善。 我不知所措,是否需要對該腳本進行進一步的改進或使代碼更簡潔。 任何幫助將不勝感激。

文件.htaccess,三個jpg和watermark.php腳本。

的.htaccess

    RewriteRule ^(.*)wp-content/uploads/(.*) $1watermark.php?src=wp-content/uploads/$2

watermark.php

<?php
$src = $_GET['src'];

    if(preg_match('/.gif/i',$src)) { $image = imagecreatefromgif($src); }
    if(preg_match('/.png/i',$src)) { $image = imagecreatefrompng($src); }
    if(preg_match('/.jpeg/i',$src)||preg_match('/.jpg/i',$src)) { $image = imagecreatefromjpeg($src); }
    if (!$image) exit();
//  if (empty($images)) die();

    if (imagesx($image) > 301 ) { $watermark = imagecreatefrompng('watermark.png'); }      // height greater than 301 then apply watermark 600x600
elseif (imagesx($image) > 175 ) { $watermark = imagecreatefrompng('watermarksm.png'); }    // height greater than 175 then apply small watermark 200x200
                           else { $watermark = imagecreatefrompng('empty.png'); }          // apply a dummy watermark resulting in none. 1x1

$dest_x = imagesx($image) - imagesx($watermark) - 0;
$dest_y = imagesy($image) - imagesy($watermark) - 0;

imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, imagesx($watermark), imagesy($watermark));
header('content-type: image/jpeg');  
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark); 
//die();
?>

我嘗試過的未在此腳本中反映的幾件事是以下“較小”更改。

if(preg_match('/.gif/i',$src))if(preg_match('/\\.gif$/i',$src))

在preg_match中嘗試的另一個變體是jpe$gjp(|e)g$ 這些變化似乎無濟於事,而且似乎進一步損害了性能。

再次,任何指導將不勝感激。 先感謝您。

為什么不一次為所有圖像創建帶水印的版本? 它將避免服務器每次在您的網站上顯示圖像時都無法工作,從而提高性能。

如果出於任何原因需要顯示原始圖像,請執行一個腳本來檢查查看器的憑據,然后返回圖像。

首先,那些正則表達式不是性能消耗。 真正的性能問題來自圖像處理。

保存結果來自imagejpeg($image); 放入世界上“隱藏”的磁盤文件中。 您可以使用.htaccess限制對該文件夾的訪問。

邏輯應該是這樣的:

<?php
// Implement getTempFile to get a path name to the hidden folder.
$tempsrc = getTempFile($src)

$tempsrcexists = file_exists($tempsrc);

if (!$tempsrcexists)
{
    // Create image on disk.
    ...
}

// At this point, the temporary file must exist.    
$fp = fopen($tempsrcexists, 'rb');

// Output data to the client from the temporary file
header("Content-type: image/jpeg");
fpassthrough($fp);

fclose($fp);

?>

這將大大減少服務器上的負載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM