Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Converts Hex color values into rgba format.
  5. *
  6. * @param string $hex
  7. * @param mixed $alpha
  8. * @return string
  9. */
  10. function hexToRgb($hex, $alpha = 0)
  11. {
  12. // remove caret symbol from the start
  13. $hex = ltrim($hex, '#');
  14.  
  15. // if short hex codes used, convert them to full length
  16. if (strlen($hex) === 3) {
  17. $hex = extendShortHex($hex);
  18. }
  19.  
  20. validateHexColor($hex);
  21.  
  22. // chunk hex value by two digits to get r, g and b values
  23. $hexArray = str_split($hex, 2);
  24.  
  25. $hexArray = array_map(function ($item) {
  26. return hexdec($item);
  27. }, $hexArray);
  28.  
  29. $hexArray['alpha'] = (float)$alpha;
  30.  
  31. return "rgb($hexArray[0], $hexArray[1], $hexArray[2], $hexArray[alpha])";
  32. }
  33.  
  34. /**
  35. * Validates hex color values by length and the digits.
  36. *
  37. * @param string $hex
  38. * @throws Error
  39. */
  40. function validateHexColor($hex)
  41. {
  42. // hex length validation
  43. if (strlen($hex) !== 6) {
  44. throw new Error('Hex code must be 6 digits long.');
  45. }
  46.  
  47. // hex digit validation
  48. if (ctype_xdigit($hex) === false) {
  49. throw new Error('Please provide a valid hex number.');
  50. }
  51. }
  52.  
  53. /**
  54. * Short hex codes are converted into six digits.
  55. *
  56. * @param string $hex
  57. * @return string
  58. */
  59. function extendShortHex($hex)
  60. {
  61. return $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement