上飛

2014-12-05 17 views
0

背景PHP水印圖像上飛

我經歷了許多網站,包括這一個一個解決辦法讀取。我有一個水印腳本,直到幾個月前,工作完美無瑕。我的託管服務提供商執行例行更新並處理了我的腳本。我做了一個調整,它工作。隨着時間的推移,水印腳本似乎在系統資源上非常沉重,導致我的網站出現各種問題,包括圖像無法隨意加載等等。目前,似乎我可以在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$。無論如何,這些變化似乎沒有幫助,似乎進一步損害了業績。

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

+0

緩存修改後的文件? – symcbean 2014-12-05 23:42:54

+0

你可以看看我的答案[這裏](http://stackoverflow.com/questions/7933262/how-to-prevent-having-the-is-not-a-valid-image-file-error-when -using-gd-functi/7933349#7933349) - 這種方式可以在不檢查文件類型的情況下打開圖像。 – Mikk 2014-12-06 00:39:10

+0

這是一個有趣的方法來清理所有'preg_match'代碼行,但不幸的是,它並沒有提高性能。 – canon 2014-12-06 02:13:28

回答

1

你爲什麼不一次爲你所有的圖像創建水印版本?它會避免服務器每次在您的網站上顯示圖像時工作,並且您將獲得更高的性能。

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

0

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

將結果從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); 

?> 

這應該減少服務器的負載顯著。