Created
May 18, 2014 18:05
-
-
Save lgladdy/da584d3a1228fa197c6c to your computer and use it in GitHub Desktop.
Converts a hex color value to a hue-compatible CIE-space-based x, y and brightness.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$hex = 'ff00ff'; | |
$rgb = hex2rgb($hex); | |
$xybri = rgbToXyBri($rgb); | |
echo $hex.' becomes x:'.$xybri['x'].', y: '.$xybri['y'].' and brightness: '.$xybri['bri']; | |
function rgbToXyBri($rgb) { | |
$r = $rgb['r']; | |
$g = $rgb['g']; | |
$b = $rgb['b']; | |
if ($r < 0 || $r > 1 || $g < 0 || $g > 1 || $b < 0 || $b > 1) { | |
throw new Exception('Invalid RGB array'); | |
} | |
$rt = ($r > 0.04045) ? pow(($r + 0.055) / (1.0 + 0.055), 2.4) : ($r / 12.92); | |
$gt = ($g > 0.04045) ? pow(($g + 0.055) / (1.0 + 0.055), 2.4) : ($g / 12.92); | |
$bt = ($b > 0.04045) ? pow(($b + 0.055) / (1.0 + 0.055), 2.4) : ($b / 12.92); | |
$cie_x = $rt * 0.649926 + $gt * 0.103455 + $bt * 0.197109; | |
$cie_y = $rt * 0.234327 + $gt * 0.743075 + $bt * 0.022598; | |
$cie_z = $rt * 0.0000000 + $gt * 0.053077 + $bt * 1.035763; | |
$hue_x = $cie_x / ($cie_x + $cie_y + $cie_z); | |
$hue_y = $cie_y / ($cie_x + $cie_y + $cie_z); | |
return array('x'=>$hue_x,'y'=>$hue_y,'bri'=>$cie_y); | |
} | |
function hex2rgb($hex) { | |
$hex = str_replace("#", "", $hex); | |
if(strlen($hex) == 3) { | |
$r = hexdec(substr($hex,0,1).substr($hex,0,1)); | |
$g = hexdec(substr($hex,1,1).substr($hex,1,1)); | |
$b = hexdec(substr($hex,2,1).substr($hex,2,1)); | |
} else { | |
$r = hexdec(substr($hex,0,2)); | |
$g = hexdec(substr($hex,2,2)); | |
$b = hexdec(substr($hex,4,2)); | |
} | |
$rgb = array('r'=>($r / 255),'g'=>($g / 255),'b'=>($b / 255)); | |
return $rgb; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment