Tag Archives: hex

PHP: Convert Web Hex Color Code to RGB Array Programming 18 OCT 2010

green php elephants - elephpantsSometimes you need to RGB array that makes up a color when working in the wonderful world of PHP. Don’t ask me why or when, though that said, I have required it at least once before when setting text color whilst generating PDFs using the FPDF library – so I have at least established that you do sometimes want to do this.

So let’s scribble down a neat little function that will convert a plain old web hex color to its RGB components for us then, shall we?

function convertHexToRGB($hex) {
    $hex = ereg_replace("#", "", $hex);
    $color = array();
    if(strlen($hex) == 3) {
            $color['r'] = hexdec(substr($hex, 0, 1));
            $color['g'] = hexdec(substr($hex, 1, 1));
            $color['b'] = hexdec(substr($hex, 2, 1));
    }
    else if(strlen($hex) == 6) {
            $color['r'] = hexdec(substr($hex, 0, 2));
            $color['g'] = hexdec(substr($hex, 2, 2));
            $color['b'] = hexdec(substr($hex, 4, 2));
    }
    return $color;
}

As you can see, the function does little more than make use of the useful hexdec function, though it neatly deals with hex codes that may or may not come in with the standard # prefix, or in the shorthand three character length instead of the standard six characters.

So now you know.

PHP: Convert a RGB color Array into a Web Hex Code Programming 15 OCT 2010

green php elephants - elephpantsRGB, that annoying little way of expressing a color via values between 0 and 255 for each of the three components that makes up a color. Always in the form of an array consisting of three values, namely one for red, one for green and one for blue, wouldn’t it be nice if we had a simple function that automatically converted such an array to the more universal web hex code? (Well when I say universal I mean developing on the web).

So let’s do that then. The following little function accepts three inputs, namely the red, green and blue values, converts each to the hexadecimal equivalent with the correct padding (remember a correct hex code is six characters long), concatenates them all together and returns a nice # prefix hex code string for us.

function convertRGBToHex($r, $g, $b) {
    $hex = "#";
    $hex.= str_pad(dechex($r), 2, '0', STR_PAD_LEFT);
    $hex.= str_pad(dechex($g), 2, '0', STR_PAD_LEFT);
    $hex.= str_pad(dechex($b), 2, '0', STR_PAD_LEFT);
    return $hex;
}

Simple, clean, and oh so useful (especially when dealing with firefox which seems to enjoy throwing color values as RGB arrays at you!).

jQuery Color Picker Plugin: Convert RGB to HEX CodeUnit 08 JUL 2010

I’ve written on the excellent jQuery Color Picker plugin from eyecon.ro before, but a question was recently raised on how to use its RGB output in code. Well actually it turns out that most browsers return its value as a standard HEX color value, but one browser in particular (and I’m not naming names here but it is the one who everyone who think themselves better than the average home user seems to love) returns the value as a RGB color string.

Annoying.

So how to deal with this then?

Well the solution is to run whatever is returned by the color picker on change through a RGB to HEX function, but a function that only fires when working on a RGB string and not a HEX string.

So lets have a look then:

//actual converter function called by main function

function toHex(N) {
	if (N==null) return "00";
	N=parseInt(N); if (N==0 || isNaN(N)) return "00";
	N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
	return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);
}

//function called to return hex string value
function RGBtoHEX(str)
{
	//check that string starts with 'rgb'
	if (str.substring(0, 3) == 'rgb') {
		var arr = str.split(",");
		var r = arr[0].replace('rgb(','').trim(), g = arr[1].trim(), b = arr[2].replace(')','').trim();
		var hex = [
			toHex(r),
			toHex(g),
			toHex(b)
		];
		return "#" + hex.join('');				
	}
	else{
		//string not rgb so return original string unchanged		
    return str;
	}
}

And there you go. Simply run all returned color values by the plugin through RGBtoHex() first, and you should be good to go with all your little DOM color style manipulations! :)

Convert FireFox Color rgb(xxx,yyy,zzz) to Hex CodeUnit 26 MAY 2010

Firefox has a nasty habit of returning element background colors and colors in general in the format

rgb(xxx,yyy,zzz)

as opposed to the normal

#xxyyzz

hexadecimal format we’ve been accustomed to seeing from the likes of Internet Exlorer and the rest of its browser ilk.

Obviously this can trip up a fair bit of your otherwise nifty jQuery or plain old vanilla Javascript driven color features and as such, is definitely something that generally does have to be dealt with by your code.

Hence the following little useful Javascript function to use on any element color or background-color retrieval call:

//Helper function to convert a digit to a two column Hex representation
function toHex(N) {
	if (N==null) return "00";
	N=parseInt(N); if (N==0 || isNaN(N)) return "00";
	N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
	return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);
}

//Function to convert rgb() format values into normal hex values
function RGBtoHEX(str)
{
	if (str.substring(0, 3) == 'rgb') {
		var arr = str.split(",");
		var r = arr[0].replace('rgb(','').trim(), g = arr[1].trim(), b = arr[2].replace(')','').trim();
		var hex = [
			toHex(r),
			toHex(g),
			toHex(b)
		];
		return "#" + hex.join('');				
	}
	else{
		return str;
	}
}

So slapping this into your code would result in you changing your calls to look like this:

alert(RGBtoHEX($('#myelement').css('color')));

As you can see by examining the inside of RGBtoHex, it will only attempt to change the values fed into it in the rgb(xxx,yyy,zzz) format. Values like the one returned by IE (i.e. #06a660) will be returned unharmed!

Nifty and useful in other words!