5

有没有办法轻松地将给定的十六进制颜色代码分配给更一般的类别(红色、绿色、蓝色、黄色、橙色、粉色、黑色、白色、灰色……)?

喜欢#ffcc55-> 橙色,#f0f0f0-> 白色,...

编辑:甚至类似于 adobe photoshop 寻找最近的网络安全颜色,因此它将颜色数量减少到 256,这已经是一个很好的解决方案!

4

2 回答 2

4

这是来自http://php.net/manual/en/function.dechex.php,来自 lavacube dot com 的 cory 的评论:

<?php

function color_mkwebsafe ( $in )
{
    // put values into an easy-to-use array
    $vals['r'] = hexdec( substr($in, 0, 2) );
    $vals['g'] = hexdec( substr($in, 2, 2) );
    $vals['b'] = hexdec( substr($in, 4, 2) );

    // loop through
    foreach( $vals as $val )
    {
        // convert value
        $val = ( round($val/51) * 51 );
        // convert to HEX
        $out .= str_pad(dechex($val), 2, '0', STR_PAD_LEFT);
    }

    return $out;
}

?>

示例:color_mkwebsafe('0e5c94'); 生产:006699

于 2012-09-19T00:10:32.000 回答
4

我不是 php 大师,所以在 php 中可能有更有效的方法来解决这个问题,但我会将每种颜色设置为一个数组,所以每个颜色类别都有 3 个数字。然后找到您建议的颜色与其他颜色之间的数学距离。保存最接近的匹配并返回它的名称。

function getcolorname($mycolor) {
    // mycolor should be a 3 element array with the r,g,b values 
    // as ints between 0 and 255. 
    $colors = array(
        "red"       =>array(255,0,0),
        "yellow"    =>array(255,255,0),
        "green"     =>array(0,255,0),
        "cyan"      =>array(0,255,255),
        "blue"      =>array(0,0,255),
        "magenta"   =>array(255,0,255),
        "white"     =>array(255,255,255),
        "grey"      =>array(127,127,127),
        "black"     =>array(0,0,0)
    );

    $tmpdist = 255*3;
    $tmpname = "none";
    foreach($colors as $colorname => $colorset) {        
        $r_dist = (pow($mycolor[0],2) - pow($colorset[0],2));
        $g_dist = (pow($mycolor[1],2) - pow($colorset[1],2));       
        $b_dist = (pow($mycolor[2],2) - pow($colorset[2],2));
        $totaldist = sqrt($r_dist + $g_dist + $b_dist);
        if ($totaldist < $tmpdist) {        
            $tmpname = $colorname;
            $tmpdist = $totaldist;
        }
    }
    return $tmpname;
}
于 2012-09-19T00:23:55.103 回答