color-utils.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. // These functions are borrowed from the colorline lib
  3. if ( ! function_exists( 'hex_to_rgb' ) ) {
  4. function hex_to_rgb( $hex ) {
  5. return sscanf( $hex, '%02X%02X%02X' );
  6. }
  7. }
  8. // RGB values: 0-255
  9. // LUM values: 0-1
  10. if ( ! function_exists( 'rgb_to_lum' ) ) {
  11. function rgb_to_lum( $rgb ) {
  12. list( $r, $g, $b ) = $rgb;
  13. return sqrt( 0.241 * $r * $r + 0.691 * $g * $g + 0.068 * $b * $b ) / 255;
  14. }
  15. }
  16. // RGB values: 0-255, 0-255, 0-255
  17. // HSV values: 0-360, 0-100, 0-100, 0-100
  18. if ( ! function_exists( 'rgb_to_hsvl' ) ) {
  19. function rgb_to_hsvl( $rgb ) {
  20. $l = rgb_to_lum( $rgb );
  21. list( $r, $g, $b ) = $rgb;
  22. $r = $r / 255;
  23. $g = $g / 255;
  24. $b = $b / 255;
  25. $max_rgb = max( $r, $g, $b );
  26. $min_rgb = min( $r, $g, $b );
  27. $chroma = $max_rgb - $min_rgb;
  28. $v = 100 * $max_rgb;
  29. if ( $chroma > 0 ) {
  30. $s = 100 * ( $chroma / $max_rgb );
  31. if ( $r === $min_rgb ) {
  32. $h = 3 - ( ( $g - $b ) / $chroma );
  33. } elseif ( $b === $min_rgb ) {
  34. $h = 1 - ( ( $r - $g ) / $chroma );
  35. } else { // $g === $min_rgb
  36. $h = 5 - ( ( $b - $r ) / $chroma );
  37. }
  38. $h = 60 * $h;
  39. return array( $h, $s, $v, $l );
  40. } else {
  41. return array( 0, 0, $v, $l );
  42. }
  43. }
  44. }
  45. if ( ! function_exists( 'change_color_luminescence' ) ) {
  46. function change_color_luminescence( $hex, $amount ) {
  47. $hex_without_hash = substr( $hex, 1, strlen( $hex ) );
  48. $rgb = hex_to_rgb( $hex_without_hash );
  49. $hsvl = rgb_to_hsvl( $rgb );
  50. return 'hsl( ' . $hsvl[0] . ',' . $hsvl[1] . '%,' . ( $hsvl[2] + $amount ) . '%)';
  51. }
  52. }