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;
}
你确定你需要整个 table 内存吗?
未测试快速:
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 内存限制的图像,就应该可以工作。
我正在使用一个函数来检查图像是否为灰度,文件路径和名称已正确加载,有时它运行良好。
但是它开始出现常见的内存耗尽错误,所以我想知道是什么原因造成的?
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;
}
你确定你需要整个 table 内存吗?
未测试快速:
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 内存限制的图像,就应该可以工作。