PHP Convert RGB from/to HTML hex color

PHP Convert RGB from/to HTML hex color
This article provides two functions for converting HTML color (like #AAED43) to three RGB values ($r = 170, $g = 237, $b = 67) and converting RGB values to HTML color.
First function, html2rgb recognizes HTML or CSS colors in format #(hex_red)(hex_green)(hex_blue), where hex_red, hex_green and hex_blue are 1 or 2-digit hex-representations of red, green or blue color components.

# character in the beginning can be omitted. Function returns array of three integers in range (0..255) or false when it fails to recognize color format.

source code: php

{ if ($color[0] == '#') $color = substr($color, 1); if (strlen($color) == 6) list($r, $g, $b) = array($color[0].$color[1], $color[2].$color[3], $color[4].$color[5]); elseif (strlen($color) == 3) list($r, $g, $b) = array($color[0], $color[1], $color[2]); else return false; $r = hexdec($r); $g = hexdec($g); $b = hexdec($b); return array($r, $g, $b); } ?>

Second function, rgb2html converts its arguments (r, g, b) to hexadecimal html-color string #RRGGBB Arguments are converted to integers and trimmed to 0..255 range. It is possible to call it with array argument rgb2html($array_of_three_ints) or specifying each component value separetly rgb2html($r, $g, $b).

source code: php

Leave a Reply


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.