2013-12-17 60 views
-2

我遇到了這個腳本的問題,我不明白。PHP顏色識別腳本返回錯誤的顏色

據我所知,一切都是正確的。該腳本可以工作,即使在一個循環中並按照預期返回顏色。

問題是顏色正在輸出不正確,...

我已刪除掃描圖像,並返回顏色陣列,並且只用預先設定的綠色作爲測試的功能。劇本認爲它更接近紅色,即使綠色值是相同的!

制定出該塊的最小色差:

function getColor($rgb) 
{ 

$colors = array(BLUE =>0x0a9ef3, RED => 0xea0a2f, GREEN => 0x336633); 

$largestDiff = 0; 
$closestColor = ""; 
foreach ($colors as $name => $rgbColor) 
{ 
    if (!isset($smallestDiff)) { 

     $smallestDiff = colorDiff($rgbColor,$rgb); 
     $closestColor = $name; 

    } else if (colorDiff($rgbColor,$rgb) < $smallestDiff) 
    { 
     $smallestDiff = colorDiff($rgbColor,$rgb); 
     $closestColor = $name; 
    } 

} 
return $closestColor; 

} 

function colorDiff($rgb1,$rgb2) 
{ 
// do the math on each tuple 

$red1 = hexdec(substr($rgb1,0,2)); 
$green1 = hexdec(substr($rgb1,2,2)); 
$blue1 = hexdec(substr($rgb1,4,2)); 

$red2 = hexdec(substr($rgb2,0,2)); 
$green2 = hexdec(substr($rgb2,2,2)); 
$blue2 = hexdec(substr($rgb2,4,2)); 

return abs($red1 - $red2) + abs($green1 - $green2) + abs($blue1 - $blue2) ; 


} 

運行使用綠色作爲測試(通常在環路)的腳本

$color = '336633'; 
$closestmatch = getColor("0x".$color); 

輸出是紅!幫幫我!

這是colorDIFF函數中的問題嗎?

+0

'Ive得到了這個劇本,我不understand.' *嘆* – SamV

+0

請問一個問題嗎?把你的想法說出來。 – user2010470

回答

1

使用$closestmatch = getColor($color);而不是$closestmatch = getColor("0x".$color);

$color = '336633'; 
echo getColor($color); // GREEN 
+0

它最初做的工作,但改變輸入顏色t'ea0a2f'我回藍時,它應該完全等於紅色! – user2010470