Advertisement
Guest User

php image luminance detector

a guest
Oct 8th, 2013
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.03 KB | None | 0 0
  1. function get_avg_luminance($filename, $num_samples=10) {
  2.     $img = imagecreatefromjpeg($filename);
  3.  
  4.     $width = imagesx($img);
  5.     $height = imagesy($img);
  6.  
  7.     $x_step = intval($width/$num_samples);
  8.     $y_step = intval($height/$num_samples);
  9.  
  10.     $total_lum = 0;
  11.  
  12.     $sample_no = 1;
  13.  
  14.     for ($x=0; $x<$width; $x+=$x_step) {
  15.         for ($y=0; $y<$height; $y+=$y_step) {
  16.  
  17.             $rgb = imagecolorat($img, $x, $y);
  18.             $r = ($rgb >> 16) & 0xFF;
  19.             $g = ($rgb >> 8) & 0xFF;
  20.             $b = $rgb & 0xFF;
  21.  
  22.             // choose a simple luminance formula from here
  23.             // http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
  24.             $lum = ($r+$r+$b+$g+$g+$g)/6;
  25.  
  26.             $total_lum += $lum;
  27.  
  28.             $sample_no++;
  29.         }
  30.     }
  31.  
  32.     // work out the average
  33.     $avg_lum  = $total_lum/$sample_no;
  34.     return $avg_lum;
  35.     // assume a medium gray is the threshold, #acacac or RGB(172, 172, 172)
  36.     // this equates to a luminance of 170
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement