Estimate required memory for libGD operation

南笙酒味 提交于 2019-12-24 04:26:22

问题


Before attempting to resize an image in PHP using libGD, I'd like to check if there's enough memory available to do the operation, because an "out of memory" completely kills the PHP process and can't be catched.

My idea was that I'd need 4 byte of memory for each pixel (RGBA) in the original and in the new image:

// check available memory
if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
     return false;
}

Tests showed that this much more memory than the library really seem to use. Can anyone suggest a better method?


回答1:


You should check this comment out, and also this one.




回答2:


I imagine it must be possible to find out GD's peak memory usage by analyzing imagecopyresampled's source code, but this may be hard, require extended profiling, vary from version to version, and be generally unreliable.

Depending on your situation, a different approach comes to mind: When resizing an image, call another PHP script on the same server, but using http:

$file = urlencode("/path/to/file");
$result = file_get_contents("http://example.com/dir/canary.php?file=$file&width=1000&height=2000"); 

(sanitizing the file parameter, obviously)

If that script fails with an "out of memory" error, you'll know the image is too large.

If it successfully manages to resize the image, it could return the path to a temporary file containing the resize result. Things would go ahead normally from there.



来源:https://stackoverflow.com/questions/3554397/estimate-required-memory-for-libgd-operation

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