Created
April 18, 2018 10:44
-
-
Save iksi/d0160fc75a528b75c3d1b1ad1081808f to your computer and use it in GitHub Desktop.
convert hex to hsl
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 | |
// http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/ | |
// convert hex to hsl | |
$hex = str_split(ltrim('#0099cc', '#'), 2); | |
// convert the rgb values to the range 0-1 | |
$rgb = array_map(function($part) { | |
return hexdec($part) / 255; | |
}, $hex); | |
// find the minimum and maximum values of r, g and b | |
$min = min($rgb); | |
$max = max($rgb); | |
// calculate the luminace value by adding the max and min values and divide by 2 | |
$l = ($min + $max) / 2; | |
if ($max === $min) { | |
$h = $s = 0; | |
} else { | |
if ($l < 0.5) { | |
$s = ($max - $min) / ($max + $min); | |
} elseif ($l > 0.5) { | |
$s = ($max - $min) / (2 - $max - $min); | |
} | |
if ($max === $rgb[0]) { | |
$h = ($rgb[1]- $rgb[2]) / ($max -$min); | |
} elseif ($max === $rgb[1]) { | |
$h = 2 + ($rgb[2]- $rgb[0]) / ($max -$min); | |
} elseif ($max === $rgb[2]) { | |
$h = 4 + ($rgb[0]- $rgb[1]) / ($max -$min); | |
} | |
$h = $h * 60; | |
if ($h < 0) { | |
$h = $h + 360; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment