MrVimes
MrVimes

Reputation: 3312

Possible to check if imagecreatefromjpeg is going to cause memory exhausted fatal error before I run it?

I've done some searching for this and I understand that it is not possible to recover from an exhausted memory fatal error. I have a script that runs imagecreatefromjpeg. I tried catching the exception, I tried running the function with @ and then checking the return value for null or false, I tried running it with 'die()'. Nothing works. So I can't 'recover' from it.

So is it possible to anticipate it before I get to it? Is it possible to check the uncompressed size of a jpeg and then die gracefully? I want to sent a message to my users along the lines of "The image $image is too large to process. You will need to create a thumbnail manually".

My shared host won't allow me to increase memory size beyond 64mb so that's not an option. My code is as follows...

function createthumb($section,$filename,$constrain=100)
{
    $dir = "$section/thumbs_$constrain";
    if(file_exists($workingdir."$section/thumbs_$constrain/$filename")) return 1; 
    if(!file_exists($dir)) mkdir($dir);

    $src = imagecreatefromjpeg($workingdir."$section/$filename");
...

Upvotes: 4

Views: 4561

Answers (4)

Adrian B
Adrian B

Reputation: 1631

You can verify string source size before imagegreatefromjpeg.

Upvotes: 0

Sander Marechal
Sander Marechal

Reputation: 23216

Have you thought about using ImageMagic instead of GD? ImageMagic is able to resize jpegs during load, so it doesn't consume copious amounts of PHP's memory. See this StackOverflow answer for details.

Upvotes: 1

BenMorel
BenMorel

Reputation: 36514

As a rule of thumb, you might use the size in pixels returned by getimagesize() :

list ($width, $height) = getimagesize($file);
$memory = $width * $height * 4; // 4 bytes per pixel

If this number is greater than a predefined limit (to be determined empirically, start with something like 32*1024*1024), then don't load it with imagecreatefromjpeg().

Upvotes: 8

zod
zod

Reputation: 12417

I think only error handler can help you as exception handling may not work on memory exhausted

http://php.net/manual/en/function.set-error-handler.php

Upvotes: 0

Related Questions