I have this Javascript function to get the correct color (white or black) for the text depending on the given HEX background color, which works well:
// Ideal color function getRGBComponents(color) { var r = color.substring(1, 3), g = color.substring(3, 5), b = color.substring(5, 7); return { R: parseInt(r, 16), G: parseInt(g, 16), B: parseInt(b, 16) }; } function idealTextColor(bgColor) { if (bgColor.length === 4) { bgColor = '#' + bgColor[1] + bgColor[1] + bgColor[2] + bgColor[2] + bgColor[3] + bgColor; } var nThreshold = 105, components = getRGBComponents(bgColor), bgDelta = (components.R * 0.299) + (components.G * 0.587) + (components.B * 0.114); return ((255 - bgDelta) < nThreshold) ? "#000000" : "#ffffff"; } idealTextColor("#123123");
I converted it to PHP:
// Ideal color function getRGBComponents($color) { $r = substr($color, 1, 3); $g = substr($color, 3, 5); $b = substr($color, 5, 7); return Array( "R" => intval($r, 16), "G" => intval($g, 16), "B" => intval($b, 16) ); } function idealTextColor($bgColor) { if (strlen($bgColor) == 4) { $bgColor = '#' . $bgColor[1] . $bgColor[1] . $bgColor[2] . $bgColor[2] . $bgColor[3] . $bgColor[3]; } $nThreshold = 105; $components = getRGBComponents($bgColor); $bgDelta = ($components["R"] * 0.299) + ($components["G"] * 0.587) + ($components["B"] * 0.114); if((255 - $bgDelta) < $nThreshold) { return "#000000"; } else { return "#FFFFFF"; } } idealTextColor("#123123");
And this does not work, it always changes # 00000 as color ( FIDDLE ). How can I fix this to work again? Or maybe someone has a better function to accomplish the same task?
source share