A safe way to prevent running out of memory of your GD image library? (Php)

Is there a way to prevent running out of memory in the PHP GD image library ? If too large an image is loaded, GD has a limited amount of memory, ending with a script. I would like him to throw a spectacular exception or something like that, but, alas, he doesn’t.

Now I am using a cobbled-together script, which first produces ini_set('memory_limit', '128M'), if this works, I am usually set up. Depending on the configuration of the server, although this may not be possible, therefore I abandon the algorithm that tries to estimate the amount of memory required (taking into account the resolution, color depth, channels and fudge ratio), then compares it with memory_get_usage()if the function exists, otherwise case a rough estimate.

All this still works, but it is far from elegant, and I'm not sure in some cases. Is there a better way to do this, i.e. If GD gracefully crashes, if necessary, instead of soaking it all up?

+5
source share
6 answers

Buy more memory! :-P

, , , , , .

.

+3

.

imagepng($image);
imagedestroy($image);

+3

, , , , , , , - , - , , .

: , : http://au2.php.net/set_error_handler#35622

+1

, , - 4 , script 2 4 , script, , . "" , ...

0

To catch fatal PHP errors, for example, "Out of memory" or "PHP Fatal error: allowed memory size is 8388608 bytes expended (tried to allocate ... bytes)", see here: http://php.net/manual/en /function.set-error-handler.php#88401

0
source

Run a few tests to check how much memory each function needs gd.

  • imagecreatetruecolorseems to be required width*height*5 bytes.

  • imagepngseems to be in need width*height*4 bytes.

0
source

All Articles