A fail-safe way to prevent GD image library from running out of memory? (PHP)

爷,独闯天下 提交于 2019-11-30 10:03:50

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.

Kevin Baker

After you create an image.

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

will remove the memory problem

There is another way to do it, but it can be time consuming, as certain parts of the image editing process would be repeated a number of times, but you can set the memory limit to your estimated value, then try to process the image, if it fails catch the exception, increase the memory limit, then process the image again - repeating this until you succeed or reach a certain memory limit - at which point you'd throw an error message to the user explaining that their image is too big to be used.

Edit: To catch the out-of-memory error, you could use this solution: http://au2.php.net/set_error_handler#35622

sebbu

Do some tests to check how much memory each gd function need.

  • imagecreatetruecolor seems to need width*height*5 bytes.

  • imagepng seems to need width*height*4 bytes.

Your best bet is to stop trying to figure out how much ram it will need, and just max it out at the outset - if you have 4 GB available, tell the image script to use between 2 and 4 GB or so, and when the script ends, have it go back to normal, that will cover off all potentially fatal situations. That's the only "Fail-safe" way I can think of anyway ...

To catch PHP's fatal errors, like "Out of memory" or "PHP Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate … bytes) in", see here : http://php.net/manual/en/function.set-error-handler.php#88401

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!