Here, I am going to explain code which is used to get HTML Color Code from RGB( RGB stands for Red, Green, and Blue) Equivalent. Mostly you get online color code Converter but sometimes you need to write a code which is used to dynamically calculate the values from RGB Equivalent and provide HTML color code.
Mostly in CSS as background or font we are using HTML Color Code and whereas if we give the user to add color, can add RGB.So, Following function will convert from the HTML color codes to the corresponding hex(hexadecimal is a base 16 numbering system) HTML Color Code.
Let’s see function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | function rgb2HEXhtml($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; $color ='#'.$color; return $color; } //you should pass r,g,b value and call function echo rgb2HEXhtml('100','200','111'); |
That’s it. Place above code into the file and run the file in browser :).
Suggested Read:
Clean HTML content in PHP
The DocType In HTML
Hope this helps someone else out.As always, thanks for reading. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.