views:

40

answers:

2

Before attempting to resize an image in PHP using libGD, I'd like to check if there's enough memory available to do the operation, because an "out of memory" completely kills the PHP process and can't be catched.

My idea was that I'd need 4 byte of memory for each pixel (RGBA) in the original and in the new image:

// check available memory
if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
     return false;
}

Tests showed that this much more memory than the library really seem to use. Can anyone suggest a better method?

A: 

I imagine it must be possible to find out GD's peak memory usage by analyzing imagecopyresampled's source code, but this may be hard, require extended profiling, vary from version to version, and be generally unreliable.

Depending on your situation, a different approach comes to mind: When resizing an image, call another PHP script on the same server, but using http:

$file = urlencode("/path/to/file");
$result = file_get_contents("http://example.com/dir/canary.php?file=$file&width=1000&height=2000"); 

(sanitizing the file parameter, obviously)

If that script fails with an "out of memory" error, you'll know the image is too large.

If it successfully manages to resize the image, it could return the path to a temporary file containing the resize result. Things would go ahead normally from there.

Pekka
+1  A: 

You should check this comment out, and also this one.

Alix Axel