2014-12-05 70 views
2

我正在處理需要檢測圖像中混合顏色百分比的應用程序。 我該如何在PHP中做到這一點? 這是一個代碼可以獲取顏色的名稱(RGB),但沒有任何百分比的混合顏色。在php中獲取混合顏色的百分比

<?php 

function colorPalette($imageFile, $numColors, $granularity = 5) 
{ 
    $granularity = max(1, abs((int)$granularity)); 
    $colors = array(); 
    $size = @getimagesize($imageFile); 
    if($size === false) 
    { 
     user_error("Unable to get image size data"); 
     return false; 
    } 
    $img = @imagecreatefromjpeg($imageFile); 
    if(!$img) 
    { 
     user_error("Unable to open image file"); 
     return false; 
    } 
    for($x = 0; $x < $size[0]; $x += $granularity) 
    { 
     for($y = 0; $y < $size[1]; $y += $granularity) 
     { 
     $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; 
     } 
     } 
    } 
    arsort($colors); 
    return array_slice(array_keys($colors), 0, $numColors); 
} 
// sample usage: 
$palette = colorPalette('te.jpg', 10, 4); 
echo "<table>\n"; 
foreach($palette as $color) 
{ 
    echo "<tr><td style='background-color:#$color;width:2em;'>&nbsp;</td><td>#$color</td></tr>\n"; 
} 
echo "</table>\n"; 
?> 

回答

0

如果你想有一個特定的顏色多少時間出現在畫面中的比例,使用類似的東西:

$sum = array_sum($palette); 
foreach($palette as $color => $count) 
{ 
    echo "<tr><td style='background-color:#$color;width:2em;'>&nbsp;</td><td>#$color (".(($count/$sum) * 100).")</td></tr>\n"; 
} 

而更換

return array_slice(array_keys($colors), 0, $numColors); 

return array_slice($colors, 0, $numColors, true); 
+0

它可能不起作用。它不能顯示它的顏色。我如何爲每種顏色寫一個if?http://webthink.ir/go/iron.php – 2014-12-05 10:14:14

+0

@MohammadJavanshah固定。 – blue112 2014-12-05 10:25:29

+0

它不起作用。我改變了它,但沒有發生。 – 2014-12-05 10:32:08

1

紅色的綠色和藍色的範圍可以從0到0xFF(255)。 Knowning是:

$red = round(round(($rgb['red']/0x33)) * 0x33); 
$green = round(round(($rgb['green']/0x33)) * 0x33); 
$blue = round(round(($rgb['blue']/0x33)) * 0x33); 

$percentRed = ($red/0xFF) * 100; 
$percentGreen = ($green/0xFF) * 100; 
$percentBlue = ($blue/0xFF) * 100; 
+0

不,我的意思是這#000000在圖像中使用20%, – 2014-12-05 09:36:31

+0

O_o?你想知道在圖像中使用了多少次特定的顏色? – blue112 2014-12-05 09:39:03

+0

@ bluee112 **是** – 2014-12-05 09:50:12