Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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");
...
like image 836
MrVimes Avatar asked Oct 17 '25 18:10

MrVimes


2 Answers

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().

like image 123
BenMorel Avatar answered Oct 19 '25 09:10

BenMorel


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.

like image 37
Sander Marechal Avatar answered Oct 19 '25 10:10

Sander Marechal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!