Advertisement
bradvin

Brightness Calc PHP

Oct 21st, 2011
3,599
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.21 KB | None | 0 0
  1. <?php
  2.  
  3.   function calc_brightness($color) {
  4.     $rgb = hex2RGB($color);
  5.     return sqrt(
  6.        $rgb["red"] * $rgb["red"] * .299 +
  7.        $rgb["green"] * $rgb["green"] * .587 +
  8.        $rgb["blue"] * $rgb["blue"] * .114);          
  9.   }
  10.  
  11.   function render_spans() {
  12.     $a = array();
  13.     $a[] = "#ffff00";
  14.     $a[] = "#336699";
  15.     $a[] = "#ffffff";
  16.     $a[] = "#000000";
  17.     $a[] = "#666666";
  18.     $a[] = "#ff00ff";
  19.     $a[] = "#00ff00";
  20.    
  21.     foreach($a as $item) {
  22.       $brightness = calc_brightness($item);
  23.       $fore_color = ($brightness < 130) ? "#FFFFFF" : "#000000";
  24.       echo '<span style="background:'.$item.'; color:'.$fore_color.'">Some Text!!!</span>';
  25.     }
  26.   }
  27.  
  28.   //http://www.php.net/manual/en/function.hexdec.php#99478
  29.   function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') {
  30.       $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
  31.       $rgbArray = array();
  32.       if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
  33.           $colorVal = hexdec($hexStr);
  34.           $rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
  35.           $rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
  36.           $rgbArray['blue'] = 0xFF & $colorVal;
  37.       } elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
  38.           $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
  39.           $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
  40.           $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
  41.       } else {
  42.           return false; //Invalid hex color code
  43.       }
  44.       return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
  45.   }  
  46.  
  47. ?>
  48.  
  49. <!doctype html>
  50. <head>
  51.     <meta charset="utf-8">
  52.     <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  53.   <title>Color Brightness PHP Test</title>
  54.   <style type="text/css">
  55.     #target_container span { padding:30px; color:#fff; display:block; width:100px; background:#000; float:left; margin:10px;}
  56.   </style>
  57. </head>
  58. <body>
  59.   <div id="target_container">
  60.     <?php render_spans(); ?>
  61.   </div>
  62. </body>
  63. </html>
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement