Php 提高此脚本的性能
所以我制作了这个脚本,它在图像中使用最多的颜色。问题是,我的编码方式让它变得毫无用处 脚本只能在小图像上找到颜色。较大的错误会导致此错误:Php 提高此脚本的性能,php,Php,所以我制作了这个脚本,它在图像中使用最多的颜色。问题是,我的编码方式让它变得毫无用处 脚本只能在小图像上找到颜色。较大的错误会导致此错误: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 36 bytes) 我在数组中插入每个像素的十六进制值。这就是问题所在,我应该如何避免使用大型阵列 剧本: $im = imagecreatefromjpeg("images/2.jpg");
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 36 bytes)
我在数组中插入每个像素的十六进制值。这就是问题所在,我应该如何避免使用大型阵列
剧本:
$im = imagecreatefromjpeg("images/2.jpg");
function common($img) {
$w = imagesx($img);
$h = imagesy($img);
$r = $g = $b = 0;
$count = 0;
$array = array();
for($y = 0; $y < $h; $y++) {
for($x = 0; $x < $w; $x++) {
$rgb = imagecolorat($img, $x, $y);
$r += $rgb >> 16;
$g += $rgb >> 8 & 255;
$b += $rgb & 255;
$hex = "#";
$hex.= str_pad(dechex($r), 2, "0", STR_PAD_LEFT);
$hex.= str_pad(dechex($g), 2, "0", STR_PAD_LEFT);
$hex.= str_pad(dechex($b), 2, "0", STR_PAD_LEFT);
$array[$count++] = $hex;
}
}
$result = array_count_values($array);
asort($result);
end($result);
$answer = key($result);
return $answer;
}
$common = common($im);
echo $common;
$im=imagecreatefromjpeg(“images/2.jpg”);
通用功能($img){
$w=图像X($img);
$h=imagesy($img);
$r=$g=$b=0;
$count=0;
$array=array();
对于($y=0;$y<$h;$y++){
对于($x=0;$x<$w;$x++){
$rgb=imagecolorat($img,$x,$y);
$r+=$rgb>>16;
$g+=$rgb>>8&255;
$b+=$rgb&255;
$hex=“#””;
$hex.=str_pad(dechex($r),2,“0”,str_pad_左);
$hex.=str_pad(dechex($g),2,“0”,str_pad_左);
$hex.=str_pad(dechex$b),2,“0”,str_pad_左);
$array[$count++]=$hex;
}
}
$result=数组\计数\值($array);
asort($结果);
结束($结果);
$answer=键($result);
返回$answer;
}
$common=common($im);
回声$普通;
与其保存阵列中的每个像素,为什么不使用计数器为每个不同的颜色只插入一个元素?比如:
if ( !isset( $array[$hex] ) )
{
$array[$hex] = 1;
}
else
{
$array[$hex]++;
}
这样,您就可以在具有最高计数的数组中找到颜色:
$highest_hex = "";
$highest_count = 0;
foreach($array AS $hex => $count)
{
if ( $count > $highest_count )
{
$highest_hex = $hex;
$highest_count = $count;
}
}
echo "The most used color has hex code {$highest_hex} and was used {$highest_count} times.";
这是一种类似字典(键值)的方法。请注意,此数组的平均大小将小于您的数组,但最坏的情况是其长度与您的相同(当所有像素具有不同的颜色且不重复时)。在这种情况下,在图像中找到的第一种颜色(左上角的第一个像素)将被视为“使用最多的颜色”。更节省内存的方法是创建一个包含文档中颜色的数组,并在每次看到颜色时增加颜色 在伪代码中:
$colors=array();
for(;$i<count($pixels);$i++){
$pixel=$pixels[$i];
if(isset($colors[getcolor($pixels[$i])]){
$colors[getcolor($pixels[$i]++;
}else{
$colors[getcolor($pixels[$i]=1;
}
}
$colors=array();
对于(;$iThe)来说,这个错误只是意味着PHP已经耗尽了内存。处理图像需要相当多的内存。你可以增加PHP允许使用的内存。我不明白为什么这个家伙会得到-4。这个错误不是很常见,问题也很复杂,尽管问题有点像:“为我做这个”但仍然不是一个坏错误。