Is there a way to prevent the PHP GD image library from running out of memory? If too large an image is uploaded, GD tends to run out of memory, terminating the script. I'd like it to throw a catchable exception or something to that extend, but alas it doesn't.
Right now I'm using a cobbled-together script that first issues an ini_set('memory_limit', '128M')
, if that works I'm usually all set. Depending on the server configuration though that may not be possible, so I'm falling back on an algorithm that tries to estimate the amount of memory needed (taking resolution, color depth, channels and a fudge factor into account), then compares it to memory_get_usage()
if the function exists, otherwise does a rough estimate.
The whole thing works so far, but it's far from elegant and will fail in some edge cases, I'm sure. Is there any better way to do this, i.e. have GD fail gracefully if it has to, instead of grinding everything to a halt?
Buy more memory! :-P
Seriously though, it is impossible to handle being out of memory because any action you take would require more memory.
Your best bet is to limit the size of image being uploaded based on the current memory settings.
After you create an image.
imagepng($image);
imagedestroy($image);
will remove the memory problem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With