如何在图像中找到主色?

php
2022-08-30 19:15:08

我想在图像中找到主色,我该怎么做?

如果我能在HEX代码中得到这个,那就太好了(例如:#eeeeee)


答案 1

要找到图像中最“主要”的颜色,即图像中最普遍的颜色:您需要创建图像的直方图。

以下是本文中有关如何在 PHP 中创建直方图的代码。(网站已经下线了好几次)

<?php
$source_file = "test_image.jpg";

// histogram options

$maxheight = 300;
$barwidth = 2;

$im = ImageCreateFromJpeg($source_file);

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

// n = total number or pixels

$n = $imgw*$imgh;

$histo = array();

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

                // get the rgb value for current pixel

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

                // extract each value for r, g, b

                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;

                // get the Value from the RGB value

                $V = round(($r + $g + $b) / 3);

                // add the point to the histogram

                $histo[$V] += $V / $n;

        }
}

// find the maximum in the histogram in order to display a normated graph

$max = 0;
for ($i=0; $i<255; $i++)
{
        if ($histo[$i] > $max)
        {
                $max = $histo[$i];
        }
}

echo "<div style='width: ".(256*$barwidth)."px; border: 1px solid'>";
for ($i=0; $i<255; $i++)
{
        $val += $histo[$i];

        $h = ( $histo[$i]/$max )*$maxheight;

        echo "<img src=\"img.gif\" width=\"".$barwidth."\"
height=\"".$h."\" border=\"0\">";
}
echo "</div>";
?> 

在这个例子中,是你最“主导”的颜色。$max


答案 2

开发了一个 PHP 类来处理这个问题,名为 color extract。但是,要知道在服务器端执行此操作将需要大量的系统资源。您可能希望改为使用画布执行此操作。


推荐