你可以使用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);
// Andres mentioned in the comments the above line only loads jpegs,
// and suggests that to load any file type you can use this:
// $img = @imagecreatefromstring(file_get_contents($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('rmnp8.jpg', 10, 4);
echo "
foreach($palette as $color)
{
echo "
#$color\n";}
echo "
\n";它给出一个数组,其值高于使用该颜色的频率。
编辑
评论者问如何使用这一目录中的所有文件,这里是:
if ($handle = opendir('./path/to/images')) {
while (false !== ($file = readdir($handle))) {
$palette = colorPalette($file, 10, 4);
echo "
foreach($palette as $color) {
echo "
#$color\n";}
echo "
\n";}
closedir($handle);
}
可能不想对太多的文件执行此操作,但它是您的服务器。
或者,如果你宁愿使用Javascript Lokesh’s Color-Theif库确实正在寻找什么。