Convert RGB values ​​to hexadecimal colors in PHP

in my code there is

$color = rgb(255, 255, 255); 

I want to convert this to a hex color code. Configure as

 $color = '#ffffff'; 
+6
source share
4 answers

Simple sprintf will do.

 $color = sprintf("#%02x%02x%02x", 13, 0, 255); // #0d00ff 

To split the format:

  • # - literal character #
  • % - start of conversion specification
  • 0 - character to be used for filling
  • 2 - the minimum number of characters that should lead to the conversion, supplemented by the above if necessary
  • x - the argument is treated as an integer and is represented as a hexadecimal number with lowercase letters
  • %02x%02x - the above four were repeated twice
+36
source

You can use the following function

 function fromRGB($R, $G, $B) { $R = dechex($R); if (strlen($R)<2) $R = '0'.$R; $G = dechex($G); if (strlen($G)<2) $G = '0'.$G; $B = dechex($B); if (strlen($B)<2) $B = '0'.$B; return '#' . $R . $G . $B; } 

Then echo fromRGB(115,25,190); will print # 7319be

Source: RGB for hexadecimal colors and hexadecimal colors for RGB - PHP

+3
source

You can try this simple piece of code below. You can also pass rgb code dynamically and in code.

 $rgb = (123,222,132); $rgbarr = explode(",",$rgb,3); echo sprintf("#%02x%02x%02x", $rgbarr[0], $rgbarr[1], $rgbarr[2]); 

This will return a code like # 7bde84

+3
source

You can try this

 function rgb2html($r, $g=-1, $b=-1) { if (is_array($r) && sizeof($r) == 3) list($r, $g, $b) = $r; $r = intval($r); $g = intval($g); $b = intval($b); $r = dechex($r<0?0:($r>255?255:$r)); $g = dechex($g<0?0:($g>255?255:$g)); $b = dechex($b<0?0:($b>255?255:$b)); $color = (strlen($r) < 2?'0':'').$r; $color .= (strlen($g) < 2?'0':'').$g; $color .= (strlen($b) < 2?'0':'').$b; return '#'.$color; } 
0
source

All Articles