2013-03-11 46 views
1

我發現了一個很棒的功能來顯示圖像中顏色的調色板。我唯一的問題是我需要能夠支持PNG和GIF文件。不知道這是否是一個簡單的解決方案。感謝任何幫助或指導。調色板PHP功能(png&gif支持)

function colorPalette($imageFile, $numColors= 5, $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; 
    } 
    $imgData = file_get_contents($imageFile); 
    $img = @imagecreatefromstring($imgData); 
    unset($imgData); 
    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); 
} 

編輯

我改變了上面的代碼,以反映我試圖完成。

這是函數如何被用來

$palette = colorPalette('image_path_here', 5); 
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"; 

信貸的功能放在這裏:http://board.phpbuilder.com/showthread.php?10355107-How-to-get-color-palette-from-images-using-PHP

+0

你能提供一個像jsfiddle這樣的工作示例的鏈接嗎?我真的很想看看它是如何工作的! – razzak 2013-03-11 20:00:52

+0

@razzak發佈了上面的工作代碼。它幾乎輸出一個類似於dribbble網站的調色板。 – souporserious 2013-03-11 20:08:11

+0

非常感謝分享,我通常使用kuller網站https://kuler.adobe.com/#create/fromanimage生成圖像的顏色主題,現在使用此代碼會更容易:)? – razzak 2013-03-11 20:24:35

回答

2

imagecreatefromjpeg有其他格式,imagecreatefrompng和imagecreatefromgif等價物。您可以查看文件擴展名並使用適當的文件擴展名。

+0

欣賞它!就是這樣。 – souporserious 2013-03-11 19:54:07