根据几个来源,所需的内存最多为每个像素 5 个字节,具体取决于几个不同的因素,例如位深度。我自己的测试证实这大致正确。
除此之外,还需要考虑一些开销。
但通过检查图像尺寸(无需加载图像即可轻松完成),我们可以粗略估计所需内存并将其与(估计)可用内存进行比较,如下所示:
$filename = 'black.jpg';
//Get image dimensions
$info = getimagesize($filename);
//Each pixel needs 5 bytes, and there will obviously be some overhead - In a
//real implementation I'd probably reserve at least 10B/px just in case.
$mem_needed = $info[0] * $info[1] * 6;
//Find out (roughly!) how much is available
// - this can easily be refined, but that's not really the point here
$mem_total = intval(str_replace(array('G', 'M', 'K'), array('000000000', '000000', '000'), ini_get('memory_limit')));
//Find current usage - AFAIK this is _not_ directly related to
//the memory_limit... but it's the best we have!
$mem_available = $mem_total - memory_get_usage();
if ($mem_needed > $mem_available) {
die('That image is too large!');
}
//Do your thing
$img = imagecreatefromjpeg('black.jpg');
这只是表面测试,所以我建议进一步测试很多不同的图像,并使用这些函数来检查计算在您的特定环境中是否相当正确:
//Set some low limit to make sure you will run out
ini_set('memory_limit', '10M');
//Use this to check the peak memory at different points during execution
$mem_1 = memory_get_peak_usage(true);