Convert HEX to RGB & RGB to HEX


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2. function HexToRGB($hex) {
  3. $hex = ereg_replace("#", "", $hex);
  4. $color = array();
  5.  
  6. if(strlen($hex) == 3) {
  7. $color['r'] = hexdec(substr($hex, 0, 1) . $r);
  8. $color['g'] = hexdec(substr($hex, 1, 1) . $g);
  9. $color['b'] = hexdec(substr($hex, 2, 1) . $b);
  10. }
  11. else if(strlen($hex) == 6) {
  12. $color['r'] = hexdec(substr($hex, 0, 2));
  13. $color['g'] = hexdec(substr($hex, 2, 2));
  14. $color['b'] = hexdec(substr($hex, 4, 2));
  15. }
  16.  
  17. return $color;
  18. }
  19.  
  20. function RGBToHex($r, $g, $b) {
  21. //String padding bug found and the solution put forth by Pete Williams (http://snipplr.com/users/PeteW)
  22. $hex = "#";
  23. $hex.= str_pad(dechex($r), 2, "0", STR_PAD_LEFT);
  24. $hex.= str_pad(dechex($g), 2, "0", STR_PAD_LEFT);
  25. $hex.= str_pad(dechex($b), 2, "0", STR_PAD_LEFT);
  26.  
  27. return $hex;
  28. }
  29. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.