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

前端 未结 6 1443
礼貌的吻别
礼貌的吻别 2020-12-31 20:01

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

相关标签:
6条回答
  • 2020-12-31 20:39

    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

    0 讨论(0)
  • 2020-12-31 20:45

    After you create an image.

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

    will remove the memory problem

    0 讨论(0)
  • 2020-12-31 20:46

    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.

    0 讨论(0)
  • 2020-12-31 20:50

    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.

    0 讨论(0)
  • 2020-12-31 20:51

    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

    0 讨论(0)
  • 2020-12-31 21:01

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

    0 讨论(0)
提交回复
热议问题