Php function hex or rgb color to color name

后端 未结 2 732
慢半拍i
慢半拍i 2021-02-06 16:50

Is there a php function that return the closest colorname by give the rgb or hex color as parameter? I have seared a lot but can\'t find a function that does that job.

P

相关标签:
2条回答
  • 2021-02-06 17:45

    there is no such function,

    you will need to write your own function that fetches the R, G and B value induvidualy, and loops them to each value and find out wat the closest is ( total of R and G and B ofset the smallest)

    you can find all HTML colornames here: http://www.w3.org/TR/SVG/types.html#ColorKeywords


    ex:

    user gives in [250,1,2] (olwost red). you have a array:

    $input = [255,1,2]
    $colors = array("red" => [255,0,0],"green"=>[0,255,0]) // used JS array to be quiker
    
    foreach( $ .. as .. $color){ // or a sort function?
    // get diff, key 0 is red key 2 is blue
    $diff = abs($input[0] - $color[0]) + ... + abs($input[2] - $color[2]); 
    }
    

    red will have a diff of: 5 + 1 + 2 green will have: 250 + 254 + 2 blue is : 250 + 1 + 253

    red has the lowest sum, so it must be colsest to red. blue is the next, and then comes green

    0 讨论(0)
  • 2021-02-06 17:48

    See my Code below. I use it to copy Logo Color to change the site theme automatically at run-time. Hope it works!

    Simply pass the image URL as parameter in the function.

    function CopyLogoColor($logo_path){
        $i = imagecreatefromjpeg($logo_path);
    
        $rTotal = 0;
        $gTotal =0;
        $bTotal = 0;
        $total = 0;
    
        for ( $x=0 ; $x<imagesx($i) ; $x++){
            for ( $y=0 ; $y<imagesy($i) ; $y++ ) {
                $rgb = imagecolorat($i,$x,$y);
                $r   = ($rgb >> 16) & 0xFF;
                $g   = ($rgb >> 8)& 0xFF;
                $b   = $rgb & 0xFF;
    
                $rTotal += $r;
                $gTotal += $g;
                $bTotal += $b;
                $total++;
    
            }
        }
    
        $rAverage = round($rTotal/$total);
        $gAverage = round($gTotal/$total);
        $bAverage = round($bTotal/$total);
    
    
    
        $r = intval($rAverage); 
        $g = intval($gAverage);
        $b = intval($bAverage);
    
        $r = dechex($r<0?0:($r>255?255:$r));
        $g = dechex($g<0?0:($g>255?255:$g));
        $b = dechex($b<0?0:($b>255?255:$b));
    
        $color = (strlen($r) < 2?'0':'').$r;
        $color .= (strlen($g) < 2?'0':'').$g;
        $color .= (strlen($b) < 2?'0':'').$b;
    
        return '#'.$color;
    
    }
    
    0 讨论(0)
提交回复
热议问题