2010-04-12 93 views
5

只是爲了好玩,我一直在尋找如何使用GD庫從圖像創建調色板。到目前爲止,我已經使用GD將用戶上傳的圖像調整爲適當的大小,以便在網頁上顯示。從圖像生成調色板

現在我希望能夠從圖像中獲得大約五種左右顏色的不同顏色,它們代表了顏色的範圍。一旦我這樣做了,我想生成一個基於這些顏色的補充調色板,然後我可以使用它來爲頁面上的不同元素着色。

任何幫助,我可以得到關於如何找到最初的調色板將不勝感激!

編輯: 我來到我自己的解決方案,你可以看到下面。

回答

8

那麼我已經花了幾天的時間擺弄,這就是我如何設計我的調色板。它對我來說工作得很好,你可以改變調色板的大小,以便從圖像中返回更多或更少的顏色。

// The function takes in an image resource (the result from one 
// of the GD imagecreate... functions) as well as a width and 
// height for the size of colour palette you wish to create. 
// This defaults to a 3x3, 9 block palette. 
function build_palette($img_resource, $palette_w = 3, $palette_h = 3) { 
    $width = imagesx($img_resource); 
    $height = imagesy($img_resource); 

    // Calculate the width and height of each palette block 
    // based upon the size of the input image and the number 
    // of blocks. 
    $block_w = round($width/$palette_w); 
    $block_h = round($height/$palette_h); 

    for($y = 0; $y < $palette_h; $y++) { 
     for($x = 0; $x < $palette_w; $x++) { 
      // Calculate where to take an image sample from the soruce image. 
      $block_start_x = ($x * $block_w); 
      $block_start_y = ($y * $block_h); 

      // Create a blank 1x1 image into which we will copy 
      // the image sample. 
      $block = imagecreatetruecolor(1, 1); 

      imagecopyresampled($block, $img_resource, 0, 0, $block_start_x, $block_start_y, 1, 1, $block_w, $block_h); 

      // Convert the block to a palette image of just one colour. 
      imagetruecolortopalette($block, true, 1); 


      // Find the RGB value of the block's colour and save it 
      // to an array. 
      $colour_index = imagecolorat($block, 0, 0); 
      $rgb = imagecolorsforindex($block, $colour_index); 

      $colour_array[$x][$y]['r'] = $rgb['red']; 
      $colour_array[$x][$y]['g'] = $rgb['green']; 
      $colour_array[$x][$y]['b'] = $rgb['blue']; 

      imagedestroy($block); 
     } 
    } 

    imagedestroy($img_resource); 
    return $colour_array; 
} 
2

這可能會幫助你

<?php 
$im = ImageCreateFromJpeg($source_file); 

$imgw = imagesx($im); 
$imgh = imagesy($im); 

// n = total number or pixels 

$n = $imgw*$imgh; 

$colors = array(); 

for ($i=0; $i<$imgw; $i++) 
{ 
     for ($j=0; $j<$imgh; $j++) 
     { 

       $rgb = ImageColorAt($im, $i, $j); 

       if (isset($colors[$rgb])) { 
        $colors[$rgb]++; 
       } 
       else { 
        $colors[$rgb] = 1; 
       } 

     } 
} 
asort($colors); 
print_r($colors);