Php检查图像是否为灰度功能内存泄漏


Php check if image is greyscale function memory leak

我正在使用一个函数来检查图像是否为灰度级,文件路径和名称是否正确加载,有时运行良好。

然而,它开始出现通常的内存耗尽错误,所以我想知道是什么导致了这种情况?

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in ... on line 51

线路51为$b[$i][$j] = $rgb & 0xFF;

我如何优化这个函数以使用更少的内存,可能只做一半的图像,然后计算出平均值,或者如果平均值太高?

function checkGreyscale(){
    $imgInfo = getimagesize($this->fileLocation);
    $width = $imgInfo[0];
    $height = $imgInfo[1];
    $r = array();
    $g = array();
    $b = array();
    $c = 0;
    for ($i=0; $i<$width; $i++) {
        for ($j=0; $j<$height; $j++) {
            $rgb = imagecolorat($this->file, $i, $j);
            $r[$i][$j] = ($rgb >> 16) & 0xFF;
            $g[$i][$j] = ($rgb >> 8) & 0xFF;
            $b[$i][$j] = $rgb & 0xFF;
            if ($r[$i][$j] == $g[$i][$j] && $r[$i][$j] == $b[$i][$j]) {
                $c++;
            }
        }
    }
    if ($c == ($width * $height))
        return true;
    else
        return false;
}

您确定需要整个表在内存中吗?

未快速测试:

function checkGreyscale(){
    $imgInfo = getimagesize($this->fileLocation);
    $width = $imgInfo[0];
    $height = $imgInfo[1];
    $r = $g = $b = 0; // defaulting to 0 before loop
    $c = 0;
    for ($i=0; $i<$width; $i++) {
        for ($j=0; $j<$height; $j++) {
            $rgb = imagecolorat($this->file, $i, $j);
            // less memory usage, its quite all you need
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            if( !($r == $g && $r == $b)) { // if not greyscale?
                return false; // stop proceeding ;)
            }
        }
    }
    return true;
}

通过这种方式,您不需要将所有图像字节存储在内存中,内存使用量可能会增加一倍以上,而是只使用运行计算的最实际的字节集。只要您根本没有加载超过php内存限制的图像,就应该有效。