Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function calc_brightness($color) {
- $rgb = hex2RGB($color);
- return sqrt(
- $rgb["red"] * $rgb["red"] * .299 +
- $rgb["green"] * $rgb["green"] * .587 +
- $rgb["blue"] * $rgb["blue"] * .114);
- }
- function render_spans() {
- $a = array();
- $a[] = "#ffff00";
- $a[] = "#336699";
- $a[] = "#ffffff";
- $a[] = "#000000";
- $a[] = "#666666";
- $a[] = "#ff00ff";
- $a[] = "#00ff00";
- foreach($a as $item) {
- $brightness = calc_brightness($item);
- $fore_color = ($brightness < 130) ? "#FFFFFF" : "#000000";
- echo '<span style="background:'.$item.'; color:'.$fore_color.'">Some Text!!!</span>';
- }
- }
- //http://www.php.net/manual/en/function.hexdec.php#99478
- function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') {
- $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
- $rgbArray = array();
- if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
- $colorVal = hexdec($hexStr);
- $rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
- $rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
- $rgbArray['blue'] = 0xFF & $colorVal;
- } elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
- $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
- $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
- $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
- } else {
- return false; //Invalid hex color code
- }
- return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
- }
- ?>
- <!doctype html>
- <head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
- <title>Color Brightness PHP Test</title>
- <style type="text/css">
- #target_container span { padding:30px; color:#fff; display:block; width:100px; background:#000; float:left; margin:10px;}
- </style>
- </head>
- <body>
- <div id="target_container">
- <?php render_spans(); ?>
- </div>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement