0

I have a simple script which watermarks hotlinking. Recently it has started eating up CPU (sometimes reaching 12% CPU usage from one user!). What can i do to minimize CPU usage?

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/');
2
  • 3
    Create an image cache by storing the watermarked image, and sending that the next time the image is requested. Commented Jul 20, 2013 at 4:06
  • @MikeW why not post that as the answer? Commented Jul 20, 2013 at 4:07

1 Answer 1

2

As @mikew beat me to saying ... cache the watermarked image.

A simple implementation of this would be

// 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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.