您获得图像中所有颜色的原因是因为您使用嵌套循环来迭代图像中的像素。相反,您应该使用两个顺序循环:一个检查水平边框,另一个检查垂直边框,因此您的循环代码将如下所示:
function checkColorAt(&$img, $x, $y, &$colors) {
$thisColor = imagecolorat($img, $x, $y);
$rgb = imagecolorsforindex($img, $thisColor);
$red = round(round(($rgb['red'] / 0x33)) * 0x33);
$green = round(round(($rgb['green'] / 0x33)) * 0x33);
$blue = round(round(($rgb['blue'] / 0x33)) * 0x33);
$thisRGB = sprintf('%02X%02X%02X', $red, $green, $blue);
if(array_key_exists($thisRGB, $colors))
{
$colors[$thisRGB]++;
}
else
{
$colors[$thisRGB] = 1;
}
}
$colors = array();
for($x = 0; $x < $size[0]; $x += $granularity)
{
checkColorAt(&$img, $x, $0, &$colors);
checkColorAt(&$img, $x, $size[1] - 1, &$colors);
}
for($y = 0; $y < $size[1]; $y += $granularity)
{
checkColorAt(&$img, $0, $y, &$colors);
checkColorAt(&$img, $size[0] - 1, $y, &$colors);
}