2011-10-11 110 views
25

如何檢測PHP中圖像的前兩種顏色?使用PHP檢測圖像的顏色

例如我有這樣的形象:

enter image description here

這個函數/過程將返回:0000FF藍色FFFF00黃色

感謝

+2

這可能是你的東西:http://stackoverflow.com/questions/3468500/detect-overall-average-color-of-the-picture – samn

+0

感謝,多數民衆贊成真棒。你能把它當作答案嗎? – Tech4Wilco

回答

20

這是一個scr ipt會給你的清單:

function detectColors($image, $num, $level = 5) { 
    $level = (int)$level; 
    $palette = array(); 
    $size = getimagesize($image); 
    if(!$size) { 
    return FALSE; 
    } 
    switch($size['mime']) { 
    case 'image/jpeg': 
     $img = imagecreatefromjpeg($image); 
     break; 
    case 'image/png': 
     $img = imagecreatefrompng($image); 
     break; 
    case 'image/gif': 
     $img = imagecreatefromgif($image); 
     break; 
    default: 
     return FALSE; 
    } 
    if(!$img) { 
    return FALSE; 
    } 
    for($i = 0; $i < $size[0]; $i += $level) { 
    for($j = 0; $j < $size[1]; $j += $level) { 
     $thisColor = imagecolorat($img, $i, $j); 
     $rgb = imagecolorsforindex($img, $thisColor); 
     $color = sprintf('%02X%02X%02X', (round(round(($rgb['red']/0x33)) * 0x33)), round(round(($rgb['green']/0x33)) * 0x33), round(round(($rgb['blue']/0x33)) * 0x33)); 
     $palette[$color] = isset($palette[$color]) ? ++$palette[$color] : 1; 
    } 
    } 
    arsort($palette); 
    return array_slice(array_keys($palette), 0, $num); 
} 

$img = 'icon.png'; 
$palette = detectColors($img, 6, 1); 
echo '<img src="' . $img . '" />'; 
echo '<table>'; 
foreach($palette as $color) { 
    echo '<tr><td style="background:#' . $color . '; width:36px;"></td><td>#' . $color . '</td></tr>'; 
} 
echo '</table>'; 
+5

你基本上只是複製了我所訪問的頁面的代碼。路要走... – samn

+3

,我增加了一個修復,但是你是正確的 – rcs20

+4

我會通過用'$ img = @imagecreatefromstring(file_get_contents($ image))替換Switch Case來優化這個功能''所以你可以處理不同的圖像類型有效... – Andres

0

如果你可以調用一個外部工具,Imagemagick可以爲你生成一個直方圖。這可能比PHP實現要快得多。

基本上,這個命令給你的顏色列表,通過最具統治力的第一排序:

convert 'http://i.stack.imgur.com/J2txV.png' -format %c histogram:info:-|sort -r 

您可能希望將圖像第一映射到一個固定的調色板(「圓關」的顏色)。這是我使用:

convert 'http://i.stack.imgur.com/J2txV.png' -modulate 100,200,100 -remap 'http://i.stack.imgur.com/GvTqB.png' -format %c histogram:info:-|sort -r