【问题标题】:Php check if image is greyscale function memory leakphp检查图像是否为灰度函数内存泄漏
【发布时间】:2015-04-01 11:44:07
【问题描述】:

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

但是它开始出现通常的内存耗尽错误,所以我想知道是什么原因造成的?

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;
}

【问题讨论】:

    标签: php image-processing memory-leaks


    【解决方案1】:

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

    未测试快速:

    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 内存限制的图像,就应该可以工作。

    【讨论】:

    • 我本以为最好测试 $r$g$b 是否不相等,如果不相等则立即返回 - 没有必要尽快检查其余部分不是灰色的 - 它必须比总是检查所有这些更快。
    猜你喜欢
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多