您可以使用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);
// 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 "<table>\n";
foreach($palette as $color)
{
echo "<tr><td style='background-color:#$color;width:2em;'> </td><td>#$color</td></tr>\n";
}
echo "</table>\n";
这会为您提供一个数组,该数组的值使用该颜色的频率较高。
编辑一个评论者问如何在目录中的所有文件上使用它,这里是:
if ($handle = opendir('./path/to/images')) {
while (false !== ($file = readdir($handle))) {
$palette = colorPalette($file, 10, 4);
echo "<table>\n";
foreach($palette as $color) {
echo "<tr><td style='background-color:#$color;width:2em;'> </td><td>#$color</td></tr>\n";
}
echo "</table>\n";
}
closedir($handle);
}
可能不想对太多文件执行此操作,但这是您的服务器。
另外,如果您更喜欢使用Javascript Lokesh的Color-Theif库,则可以完全满足您的需求。
0
我有一个jpg图片。
我需要知道图像的总体颜色。乍一看,可以使用图像的直方图(通道RGB)。
在工作中,我主要使用JavaScript和PHP(少量Python),因此欢迎使用这些语言的决定。也许这是用于处理类似问题的图像的库。
我不需要动态确定图片的颜色。我只需要遍历整个图像阵列并分别确定每个图像的颜色(我将记住这些信息以备将来使用)。