Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group similar hex codes in PHP

Tags:

php

hex

colors

I have the following color codes:

f3f3f3
f9f9f9

Visually, these two color codes are similar. How can I group them into a single color, or to delete one of them?

If I try to use base_convert($hex, 16, 10) and get the difference between the values, the problem is that some colors are similar as int value but really different visually. For example:

#484848 = 4737096 (grey)
#4878a8 = 4749480 (blue) - visually there is a huge difference, but as int value the difference is small

and

#183030 = 1585200 (greyish)
#181818 = 1579032 (greyish) - both ways is fine

#4878a8 = 4749480 (blue)
#a81818 = 11016216 (red) - the difference is huge, both visual and as int value

like image 465
Doctor Jim Avatar asked Dec 06 '12 16:12

Doctor Jim


1 Answers

Use hexdec function to convert a hexa decimal color code to its RGB equivalent. example (taken from hexdec page) :

<?php
/**
 * Convert a hexa decimal color code to its RGB equivalent
 *
 * @param string $hexStr (hexadecimal color value)
 * @param boolean $returnAsString (if set true, returns the value separated by the separator character. Otherwise returns associative array)
 * @param string $seperator (to separate RGB values. Applicable only if second parameter is true.)
 * @return array or string (depending on second parameter. Returns False if invalid hex color value)
 */                                                                                                 
function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') {
    $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
    $rgbArray = array();
    if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
        $colorVal = hexdec($hexStr);
        $rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
        $rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
        $rgbArray['blue'] = 0xFF & $colorVal;
    } elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
        $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
        $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
        $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
    } else {
        return false; //Invalid hex color code
    }
    return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
} ?>

OUTPUT:

hex2RGB("#FF0") -> array( red =>255, green => 255, blue => 0)
hex2RGB("#FFFF00) -> Same as above
hex2RGB("#FF0", true) -> 255,255,0
hex2RGB("#FF0", true, ":") -> 255:255:0

than, get the red,green,and blue deltas, to get the colors distance.

like image 185
Kuf Avatar answered Sep 21 '22 21:09

Kuf