1

画像内の色のパレットを表示する素晴らしい機能を見つけました。私の唯一の問題は、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

4

1 に答える 1

2

imagecreatefromjpeg には、imagecreatefrompng と imagecreatefromgif という他の形式に相当するものがあります。ファイル拡張子を見て、適切なものを使用できます。

于 2013-03-11T19:42:05.953 に答える