Posted By

Cory on 01/16/08


Tagged

php image gd hex color RGB


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

kiwiscanfly
vali29
nikel303


Convert HEX to RGB & RGB to HEX


 / Published in: PHP
 

  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
Posted By: KyleFarris on March 25, 2009

Oooh... thank you very much. :)

Posted By: kiwiscanfly on April 21, 2009

Thank you!

Posted By: kiwiscanfly on April 21, 2009

Thank you!

Posted By: PeteW on July 20, 2010

I'm afraid there's a bug in RGBToHex.

You need to pad each hex value, otherwise your full hex number could end up being 3, 4 or 5 digits.

For instance, the following would both generate #22222, despite being different colours: RGBToHex (2, 34, 34); RGBToHex (34, 34, 2);

Try this:

function RGBToHex($r, $g, $b) { $hex = "#"; $hex.= strpad(dechex($r), 2, '0', STRPADLEFT ); $hex.= strpad(dechex($g), 2, '0', STRPADLEFT ); $hex.= strpad(dechex($b), 2, '0', STRPAD_LEFT );

    return $hex;
}
Posted By: PeteW on July 20, 2010

I'm afraid there's a bug in RGBToHex.

You need to pad each hex value, otherwise your full hex number could end up being 3, 4 or 5 digits.

For instance, the following would both generate #22222, despite being different colours: RGBToHex (2, 34, 34); RGBToHex (34, 34, 2);

Try this: function RGBToHex($r, $g, $b) { $hex = "#"; $hex.= strpad(dechex($r), 2, '0', STRPADLEFT ); $hex.= strpad(dechex($g), 2, '0', STRPADLEFT ); $hex.= strpad(dechex($b), 2, '0', STRPAD_LEFT );

    return $hex;
}

Posted By: PeteW on July 20, 2010

Meh, Snipplr doesn't seem to want to display my code properly, but hopefully you get the idea.

Posted By: Cory on October 16, 2010

Cool thanks for that info on the bug I fixed the issue.

Posted By: indeed on December 3, 2011

Thank you!

Posted By: J0ker on December 10, 2011

in the line 3 use better str_replace

You need to login to post a comment.