| ||||||
|
How to convert RGB Color Codes into a HTML Readable Hex Format in PHP
This tutorial will teach you on the one hand how to convert decimal numbers into hexadecimals codes and vise versa, while at the same time having a closer look at the format of HTML Color codes. While the RGB to HTML Color Code, and HTML Color Code to RGB conversion will require some coding, PHP provides two functions with which decimal numbers can be converted into hexadecimals and vise versa: // Hexadecimal to Decimal $dec = hexdec($hex); //Decimal to Hexadecimal $hex = dechex($dec); As mentioned the conversion of a RGB to HTML Color Code is a bit more complex than simply converting decimals to hexadecimals, specifically since HTML Color codes have to contain either 6 or 3 alphanumeric symbols. As you can see from the function in our example each of the RGB numbers is converted into the respective 2 alphanumeric symbols in the HTML color code. If the result happens to be a single symbol, we will bump it up with a 0: function RGB_to_Hex($RGB1, $RGB2, $RGB3) { $hex1 = dechex($RGB1); if(strlen($hex1) == 1){ $hex1 = "0".$hex1; } $hex2 = dechex($RGB2); if(strlen($hex2) == 1){ $hex2 = "0".$hex2; } $hex3 = dechex($RGB3); if(strlen($hex3) == 1){ $hex3 = "0".$hex3; } return "#".$hex1.$hex2.$hex3; } We will now use the following code to call upon this function: <div style="background:<?php echo RGB_to_Hex(1, 108, 154); ?>; width:300px; height:100px; text-align:center; border:1px #000 solid;">RGB_to_Hex(1, 108, 154)</div> <br> <div style="background:<?php echo RGB_to_Hex(1, 141, 49); ?>; width:300px; height:100px; text-align:center; border:1px #000 solid;">RGB_to_Hex(0, 141, 49)</div> <br> <div style="background:<?php echo RGB_to_Hex(163, 1, 28); ?>; width:300px; height:100px; text-align:center; border:1px #000 solid;">RGB_to_Hex(163, 1, 28)</div> <br> <div style="background:<?php echo RGB_to_Hex(243, 247, 1); ?>; width:300px; height:100px; text-align:center; border:1px #000 solid;">RGB_to_Hex(243, 247, 1)</div> <br> The result: RGB_to_Hex(1, 108, 154) RGB_to_Hex(0, 141, 49) RGB_to_Hex(163, 1, 28) RGB_to_Hex(243, 247, 1) Here then is our function to convert hexadecimal number codes into RGB codes. It is a little less complex than the previous task: function Hex_to_RGB($hex) { $RGB1 = hexdec($hex[1].$hex[2]); $RGB2 = hexdec($hex[3].$hex[4]); $RGB3 = hexdec($hex[5].$hex[6]); return $RGB1.", ".$RGB2.", ".$RGB3; } Here are the results of a few test trials: Hex to RGB #ffffff = 255, 255, 255 #000000 = 0, 0, 0 #016c9a = 1, 108, 154 #018d31 = 1, 141, 49 #a3011c = 163, 1, 28 #f3f701 = 243, 247, 1
|