Categories
General

Speeding up GD when making 2 sizes

Summary: If you’re using GD to generate 2 image sizes from an original, first generate the larger resized image, then generate the smaller size based on the resized image (not the original) to save a tiny bit of execution time.

I’m working on a webcam project where I need to pull in a large webcam image and resize it to 2 smaller sizes. The first user to visit the webcam page in a while triggers a resize, so speeding up the resize operation means they won’t have to wait long for the page to appear.

First, to get the execution time for a block of PHP code:

$startexec = microtime(true);

/* code you want to measure goes here */

$endexec = microtime(true) - $startexec;

This is for PHP 5+ – see the microtime entry in the manual if you’re working with an earlier PHP version.

There are a lot of ways to fetch a remote image, such as fopen() and CURL, but imagecreatefromjpeg($url) has been working fine for me so far. Here’s the code to get the external image, resample it, delete the old resized image if it exists, then write out the new version.

$bigimage = imagecreatefromjpeg($bigpath);

$midimage = imagecreatetruecolor($midwidth,$midheight);

imagecopyresampled($midimage,$bigimage,0,0,0,0,
$midwidth,$midheight,$bigwidth,$bigheight);

if (is_file($midpath))
unlink($midpath);

imagejpeg($midimage, $midpath);

On my testing machine it was taking about 1.2 seconds to do this twice, using a 2048×1536 original to generate both smaller-sized images. I found that by doing the mid-sized resample first, then using the mid-sized image for the smaller resample, resulted in a slightly faster execution time of a little less than 1 second.

That’s not much of an improvement, so next I’m going to investigate using ImageMagick instead of GD since that could be twice as fast.

Update: After a bit of testing I’m not seeing much difference between using GD (around 0.88 seconds) and ImageMagick (around 0.75 seconds), at least for the sort of resizing I’m doing – from 2048×1536 down to 850×638 and 500×375.

Avatar photo

By isaac

I like cats. he/him