2013-07-20 59 views
0

我有一個簡單的腳本,其中水印盜鏈。最近它開始吃掉CPU(有時達到12%CPU使用率!)。我能做些什麼來最大限度地減少CPU使用使用了PHP的腳本CPU

set_time_limit (3); 
if(!empty($_GET['e'])){ 
    $data = getimagesize("images/".$_GET['e']); 

    // create base image 
    $base_image = imagecreatetruecolor($data[0],$data[1]); 
    $photo = imagecreatefromjpeg("images/".$_GET['e']); 
    $top_image = imagecreatefrompng('watermark.png'); 
    imagesavealpha($top_image, true); 
    imagealphablending($top_image, true); 
    imagesavealpha($base_image, true); 
    imagealphablending($base_image, true); 
    $data2 = getimagesize('watermark.png'); 

    // merge images 
    imagecopy($base_image, $photo, 0, 0, 0, 0, $data[0], $data[1]); 
    imagecopy($base_image, $top_image, 0, 0, 0, 0, $data2[0], $data2[1]); 

    // return file 
    header('Content-Type: image/png'); 
    imagepng($base_image); 
} else 
    header('Location: http://www.mydomain.com/'); 
+3

通過存儲水印圖像,併發送下一次的圖像被要求創建一個圖像緩存。 – 2013-07-20 04:06:27

+0

@MikeW爲什麼不作爲答案張貼? – Orangepill

回答

2

由於@mikew打我說...緩存水印圖像。

一個簡單的實現,這將是

// get the file extension and set some convience variables 
$ext = substr($_GET["e"], strrpos($_GET["e"], ".")+1); 
$cacheFile = "images/wm/".$_GET['e']; 
$srcFile = "images/".$GET["e"]; 
// check to see if the file exists in the watermark directory 
if (!file_exists($cacheFile)){ 
    // do sweet image processing magic if cache file doesn't exist and create the cache file 
    $data = getimagesize($srcFile); 
    // create base image 
    $base_image = imagecreatetruecolor($srcFile); 
    $photo = imagecreatefromjpeg($srcFile); 
    $top_image = imagecreatefrompng('watermark.png'); 
    imagesavealpha($top_image, true); 
    imagealphablending($top_image, true); 
    imagesavealpha($base_image, true); 
    imagealphablending($base_image, true); 
    $data2 = getimagesize('watermark.png'); 

    // merge images 
    imagecopy($base_image, $photo, 0, 0, 0, 0, $data[0], $data[1]); 
    imagecopy($base_image, $top_image, 0, 0, 0, 0, $data2[0], $data2[1]); 

    switch($ext){ 
     case "jpg": 
     case "jpeg": 
      header("Content-Type: image/jpeg"); 
      imagejpeg($base_image, $cacheFile); 
      break; 
     case "png": 
      header("Content-Type: image/png"); 
      imagepng($base_image, $cacheFile); 
      break; 
    } 
} 
// output the cached file. 
readfile($cacheFile);