Search code examples
phpgraphicsimage-processingimagemagickgraphicsmagick

Most Efficient Way to Create Thumbnails?


I have a huge volume of thumbnailing to do. Currently, I am using ImageMagick, but it's proving too inefficient (it's too slow, uses too much CPU/memory, etc.).

I have started to evaluate GraphicsMagick, which I expected to get "wow" results from. I didn't get them. Can someone take a quick look at my benchmark script (does simple speed and file size comparison only; no CPU and memory checks yet):

http://pastebin.com/2gP7Eaxc

Here's a sample output I got:

'gm convert' took 75.0039 seconds to execute 10 iteration(s).
'convert' took 83.1421 seconds to execute 10 iteration(s).
Average filesize of gm convert: 144,588 bytes.
Average filesize of convert: 81,194 bytes. 

GraphicsMagick is not that much faster -- and the outputted file sizes are SIGNIFICANTLY higher than ImageMagick.


Solution

  • I you want to use GD2, try this function I use. It's pretty easy to use:

    function scaleImage($source, $max_width, $max_height, $destination) {
        list($width, $height) = getimagesize($source);
        if ($width > 150 || $height > 150) {
        $ratioh = $max_height / $height;
        $ratiow = $max_width / $width;
        $ratio = min($ratioh, $ratiow);
        // New dimensions
        $newwidth = intval($ratio * $width);
        $newheight = intval($ratio * $height);
    
        $newImage = imagecreatetruecolor($newwidth, $newheight);
    
        $exts = array("gif", "jpg", "jpeg", "png");
        $pathInfo = pathinfo($source);
        $ext = trim(strtolower($pathInfo["extension"]));
    
        $sourceImage = null;
    
        // Generate source image depending on file type
        switch ($ext) {
            case "jpg":
            case "jpeg":
            $sourceImage = imagecreatefromjpeg($source);
            break;
            case "gif":
            $sourceImage = imagecreatefromgif($source);
            break;
            case "png":
            $sourceImage = imagecreatefrompng($source);
            break;
        }
    
        imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    
        // Output file depending on type
        switch ($ext) {
            case "jpg":
            case "jpeg":
            imagejpeg($newImage, $destination);
            break;
            case "gif":
            imagegif($newImage, $destination);
            break;
            case "png":
            imagepng($newImage, $destination);
            break;
        }
        }
    }