<?php
// image_bargraph.php
// Read image colours into bargraph
// RJM Programming
// April, 2015

set_time_limit(0);
$harray = array();
$cstring = ",0,#ffffff,";
$one=1;
$bmpfile = "";
$cont = "";
$goes = 0;
$biggest=-1;
$smallest=-1;
$fz = 0;
$imgstr="";
$dbbi="";
$oldbbi="";

$im = null;

function htmlis() {
  global $bmpfile, $cstring, $dbbi;
  
  // ,64,#0f0d12,63,#080b10,63,#090c11,63,#0d0b0e,63,#0c0a0d,63
  
  $things = explode(",#", $cstring);
  
  $hstr="<html><head><script type='text/javascript'> function onld() { " . $dbbi . "  if (document.URL.indexOf('?d=0') != -1) {   top.document.getElementById('aread').value=1.0; top.document.getElementById('mymeter').value=1.0;   }  location.href='http://www.rjmprogramming.com.au/PHP/BarChart/bar_chart.php?title=" . str_replace(" ", "%20", $bmpfile) . "&label=RGB%20Frequency&value=Frequency&data=";
  // ,%20[~ffffff~,11]%20,%20[~000000~,22]
  for ($ii=1; $ii<sizeof($things); $ii++) {
   $nums=explode(",", $things[-1 + $ii]);
   $cols=explode(",", $things[$ii]);
   if (strlen($cols[0]) == 6 && strpos($hstr, ",%20[~" . $cols[0] . "~,") === false && strpos($cstring, ",#" . $cols[0] . ",") !== false) $hstr .= ",%20[~" . $cols[0] . "~," . $nums[sizeof($nums) - 1] . "]";
  }
  $hstr .= "'; } </script></head><body onload=' onld(); '></body></html> \n";
  try {
    file_put_contents("bmpso" . server_remote_addr() . ".htm", $hstr);
  } catch(Exception $e) {
  }
  try {
    file_put_contents("bmpso" . server_remote_addr() . ".html", $hstr);
  } catch(Exception $ee) {
  }
}

function outhex($inr, $ing, $inb) {
  $outr=dechex($inr);
  if (strlen($outr) == 1) $outr = "0" . dechex($inr);
  $outg=dechex($ing);
  if (strlen($outg) == 1) $outg = "0" . dechex($ing);
  $outb=dechex($inb);
  if (strlen($outb) == 1) $outb = "0" . dechex($inb);
  return "#" . $outr . $outg . $outb;
}

// Thanks to http://php.net/manual/en/function.imagecolorat.php for trimImage() below ...
function trimImage($im,$c,$t) {
  // if trim colour ($c) isn't a number between 0 - 255
  if (!is_numeric($c) || $c < 0 || $c > 255) {
    // grab the colour from the top left corner and use that as default
    $rgb = imagecolorat($im, 2, 2); // 2 pixels in to avoid messy edges
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;
    $c = round(($r+$g+$b)/3); // average of rgb is good enough for a default
  }
  // if tolerance ($t) isn't a number between 0 - 255 use 10 as default
  if (!is_numeric($t) || $t < 0 || $t > 255) $t = 10;

  $w = imagesx($im); // image width
  $h = imagesy($im); // image height
  for($x = 0; $x < $w; $x++) {
    for($y = 0; $y < $h; $y++) {
      $rgb = imagecolorat($im, $x, $y);
      $r = ($rgb >> 16) & 0xFF;
      $g = ($rgb >> 8) & 0xFF;
      $b = $rgb & 0xFF;
      if (
      ($r < $c-$t || $r > $c+$t) && // red not within tolerance of trim colour
      ($g < $c-$t || $g > $c+$t) && // green not within tolerance of trim colour
      ($b < $c-$t || $b > $c+$t) // blue not within tolerance of trim colour
      ) {
        // using x and y as keys condenses all rows and all columns
        // into just one X array and one Y array.
        // however, the keys are treated as literal and therefore are not in
        // numeric order, so we need to sort them in order to get the first
        // and last X and Y occurances of wanted pixels.
        // normal sorting will remove keys so we also use x and y as values,
        // this way they are still available without preserving keys.
        $y_axis[$y] = $y; 
        $x_axis[$x] = $x;
        // note: $y_axis[] = $y; and $x_axis[] = $x; works just as well
        // but results in much much larger arrays than is necessary
        // array_unique would reduce size again but this method is quicker
      }
    }
  }
  // sort them so first and last occurances are at start and end
  sort($y_axis);
  sort($x_axis); 

  $top = array_shift($y_axis); // first wanted pixel on Y axis
  $right = array_pop($x_axis); // last wanted pixel on X axis
  $bottom = array_pop($y_axis); // last wanted pixel on Y axis
  $left = array_shift($x_axis); // first wanted pixel on X axis

  return array($top,$right,$bottom,$left);
}

function server_remote_addr() {
    $rma = $_SERVER['REMOTE_ADDR'];
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    // you can add different browsers with the same way ..
    if(preg_match('/(chromium)[ \/]([\w.]+)/', $ua))
            $rma = '000000'.$rma;
    elseif(preg_match('/(chrome)[ \/]([\w.]+)/', $ua))
            $rma = '00000'.$rma;
    elseif(preg_match('/(safari)[ \/]([\w.]+)/', $ua))
            $rma = '0000'.$rma;
    elseif(preg_match('/(opera)[ \/]([\w.]+)/', $ua))
            $rma = '000'.$rma;
    elseif(preg_match('/(msie)[ \/]([\w.]+)/', $ua))
            $rma = '00'.$rma;
    elseif(preg_match('/(mozilla)[ \/]([\w.]+)/', $ua))
            $rma = '0'.$rma;
    return str_replace(":", "_", str_replace(".", "_", $rma));
}

if (isset($_GET['reading'])) {
  $grst = urldecode($_GET['reading']);
  $grs = explode(" ", $grst);
  $gr = $grs[0];
  if (file_exists("bmpso" . server_remote_addr() . ".far")) {
    $gr = "";
    while ($gr == "") {
      if (!file_exists("bmpso" . server_remote_addr() . ".far")) {
        $goes++;
        if ($goes == 5) $gr = "1.0";
      } else {
        $goes = 0;
        $grst = @file_get_contents("bmpso" . server_remote_addr() . ".far");
        $grs = explode(" ", $grst);
        $gr = $grs[0];
      }
    }
    echo "<!doctype html><html><body onload=\" " . $dbbi . " parent.document.getElementById('aread').value=" . $gr . "; parent.document.getElementById('mymeter').value=" . $gr . ";\"></body></html>"; 
  } else if ($gr == "1.0" || $gr == "1") {
    echo "<!doctype html><html><body onload=\" " . $dbbi . " top.document.getElementById('aread').value=1.0; top.document.getElementById('mymeter').value=1.0; parent.document.getElementById('myiframetwo').style.display='block';  parent.document.getElementById('myiframe').style.display='NONE'; parent.document.getElementById('myiframe').src='http://www.rjmprogramming.com.au';\"></body></html>"; 
  } else {
    echo "<!doctype html><html><body onload=\" " . $dbbi . " parent.document.getElementById('aread').value=" . $gr . "; parent.document.getElementById('mymeter').value=" . $gr . ";\"></body></html>"; 
  }
  exit;
} else if (isset($_GET['bmpfile'])) {
  $bmpfile = urldecode($_GET['bmpfile']);
  $dbbi=" parent.document.getElementById('xbod').style.backgroundImage=\"url('" . $bmpfile . "')\"; ";
  $ondbbi=" onload=parent.document.getElementById('xbod').style.backgroundImage=\"url('" . $bmpfile . "')\";";
  if (file_exists("bmpso" . server_remote_addr() . ".far")) unlink("bmpso" . server_remote_addr() . ".far");
  try {
  file_put_contents("bmpso" . server_remote_addr() . ".html", "<html><body><div align='center'>Bar Graph Coming Soon ...</div></body></html>");
  } catch (Exception $aq1) { }
  try {
  file_put_contents("bmpso" . server_remote_addr() . ".htm", "<html><body><div align='center'>Bar Graph Coming Soon ...</div></body></html>");
  } catch (Exception $aq2) { }
} else if (isset($_POST['bmpfile'])) {
  $bmpfile = urldecode($_POST['bmpfile']);
  $dbbi=" parent.document.getElementById('xbod').style.backgroundImage=\"url('" . $bmpfile . "')\"; ";
  $ondbbi=" onload=parent.document.getElementById('xbod').style.backgroundImage=\"url('" . $bmpfile . "')\";";
  if (file_exists("bmpso" . server_remote_addr() . ".far")) unlink("bmpso" . server_remote_addr() . ".far");
  try {
  file_put_contents("bmpso" . server_remote_addr() . ".html", "<html><body" . $ondbbi . "><div align='center'>Bar Graph Coming Soon ...</div></body></html>");
  } catch (Exception $aq3) { }
  try {
  file_put_contents("bmpso" . server_remote_addr() . ".htm", "<html><body" . $ondbbi . "><div align='center'>Bar Graph Coming Soon ...</div></body></html>");
  } catch (Exception $aq4) { }
} else {
  if (file_exists("bmpso" . server_remote_addr() . ".far")) {
    unlink("bmpso" . server_remote_addr() . ".far");
  }
  try {
  file_put_contents("bmpso" . server_remote_addr() . ".html", "<html><body" . $ondbbi . "><div align='center'>Bar Graph Coming Soon ...</div></body></html>");
  } catch (Exception $aq5) { }
  try {
  file_put_contents("bmpso" . server_remote_addr() . ".htm", "<html><body" . $ondbbi . "><div align='center'>Bar Graph Coming Soon ...</div></body></html>");
  } catch (Exception $aq6) { }
  echo "<!doctype html><html><head><title>Read image colours into bargraph with progress bar - RJM Programming - April, 2015</title><link href='//www.rjmprogramming.com.au/PHP/emboss_h1.css' rel='stylesheet' type='text/css'><script type='text/javascript'> var sto=null; var cnt=1; var suffix='l'; var aread=0; function check() { aread=document.getElementById('aread').value; var isd=new Date().toJSON().slice(0,21); if (aread >= 1.0) { isd='0'; }   parent.document.getElementById('myiframetwo').style.display='block';  if (isd.indexOf('5.') != -1 || isd.indexOf('1.') != -1 || aread == 1.0) { parent.document.getElementById('myiframetwo').src='bmpso" . server_remote_addr() . ".htm' + suffix + '?d=' + isd; if (suffix == 'l') { suffix=''; } else { suffix='l'; } } document.getElementById('myiframe').src='./image_bargraph.php?reading=' + aread;  if (aread == 1.0) { clearInterval(sto); aread=1.01; }  } </script></head><body id='xbod' style=' background-color:white; ' onload='sto=setInterval(check,7000);'><h1 align='center'>Image File Colour Bar Graph - RJM Programming - April, 2015</h1><br><div align='center'><span><form target='myiframe' action='./image_bargraph.php' method='POST'>Image File (http:// or file:// syntax accepted (or a local image file)): <input type='text' id='bmpfile' name='bmpfile' value='http://'></input><input onclick=\"document.getElementById('myiframe').src='http://www.rjmprogramming.com.au'; if (sto != null) { clearInterval(sto); sto=setInterval(check,7000); }  \" type='submit' value='Create Bar Graph'></input><input type='hidden' id='aread' name='aread' value='0'></input></form>" . $imgstr . "</span><br><meter id='mymeter' value='0'></meter><br><br><iframe height=400 width=750 id='myiframetwo' src='javascript:none;' style='display:none;'></iframe><br><iframe id='myiframe' src='javascript:none;' style='display:none;'></iframe></div></body></html>"; 
  exit;
}

if ($bmpfile != "") {
   file_put_contents("bmpso" . server_remote_addr() . ".farit", "-3");
if (strpos((strtolower($bmpfile) . "*"), ".jpg*") === false && strpos((strtolower($bmpfile) . "*"), ".jpeg*") === false && strpos((strtolower($bmpfile) . "*"), ".bmp*") === false && strpos((strtolower($bmpfile) . "*"), ".gif*") === false && strpos((strtolower($bmpfile) . "*"), ".png*") === false) {
  $bmpfile = "";
} else if (strpos(("*" . strtolower($bmpfile)), "*http://") !== false || strpos(("*" . strtolower($bmpfile)), "*https://") !== false) {
  $cont = @file_get_contents($bmpfile);
  $fz = -1;
} else if (strpos(("*" . strtolower($bmpfile)), "*file://") !== false) {
  $bmpfile = substr($bmpfile, 7);
  if ($bmpfile != "") {
    if (substr($bmpfile, 0, 1) == ".") {
      $bmpfile = dirname(__FILE__) . "/" . $bmpfile;
      if (!file_exists($bmpfile)) $bmpfile = "";
    } else if (!file_exists($bmpfile)) {
      $bmpfile = "";
    }
  }
} else if ($bmpfile != "") {
  if (!file_exists($bmpfile)) $bmpfile = "";
}

if ($cont == "" && $bmpfile != "") {
   file_put_contents("bmpso" . server_remote_addr() . ".farit", "-2");
  $cont = @file_get_contents($bmpfile);
   file_put_contents("bmpso" . server_remote_addr() . ".farit", "-1");
  $fz = filesize($bmpfile);
   file_put_contents("bmpso" . server_remote_addr() . ".farit", "0" . $fz);
    // Thanks to http://php.net/manual/en/function.imagecolorat.php
  if (strpos($bmpfile, ".jp") !== false) {
   $im = imagecreatefromjpeg($bmpfile); // we need resource
  } else if (strpos($bmpfile, ".gif") !== false) {
   $im = imagecreatefromgif($bmpfile); // we need resource
  } else if (strpos($bmpfile, ".bmp") !== false) {
   $im = imagecreatefromwbmp($bmpfile); // we need resource
  } else if (strpos($bmpfile, ".png") !== false) {
   $im = imagecreatefrompng($bmpfile); // we need resource
  } else {
   $im = imagecreatefromstring($cont); // we need resource
   if ($fz <= 0) $fz = strlen($cont);
  }  
}

if ($cont != "" && ($fz > 54 || $fz < 0)) {
 /* if ($fz < 0) {
   $i = 54;
   try {
     $x = substr($cont, $i, 1);
     while ($i > 0) {
       $x = substr($cont, $i, 1);
       try {
      if ($biggest < 0) {
        $biggest = $x;
        $smallest = $x;
      } else if ($biggest < $x) {
        $biggest = $x;
      } else if ($smallest > $x) {
        $smallest = $x;
      }
         $harray[$x] = $harray[$x] + 1;
       } catch (Exception $ex) {
         $harray[$x] = 1;
       }
       $i = $i + 1;
       if (($i % 54) == 0) file_put_contents("bmpso" . server_remote_addr() . ".far", ($i / $fz));
     }
     unlink("bmpso" . server_remote_addr() . ".far");
     file_put_contents("bmpso" . server_remote_addr() . ".fargo", $smallest . " vs " . $biggest);
     echo "<!doctype html><html><body onload=\"parent.document.getElementById('bmpfile').value='" . $smallest . " vs " . $biggest . "'; parent.document.getElementById('mymeter').value=1.0;\"></body></html>"; 
     exit;
   } catch (Exception $exzero) {
     var_dump($harray);
   }
  } else */ {
  

   file_put_contents("bmpso" . server_remote_addr() . ".farit", "1");
  // Thanks to http://php.net/manual/en/function.imagecolorat.php
  //$im = imagecreatefromjpeg($bmpfile); // we need resource
   file_put_contents("bmpso" . server_remote_addr() . ".farit", "2");

  $c = (isset($_GET[c])) ? $_GET[c] : null; // set trim colour via GET
  $t = (isset($_GET[t])) ? $_GET[t] : null; // set tolerance via GET
   file_put_contents("bmpso" . server_remote_addr() . ".farit", "3");

  list($t,$r,$b,$l) = trimImage($im,$c,$t); // find top, right, bottom and left
   file_put_contents("bmpso" . server_remote_addr() . ".farit", "4");


  $k = 0;
  $w = $r-$l; // find width
  $h = $b-$t; // find height
   file_put_contents("bmpso" . server_remote_addr() . ".farit", ($w * $h));
  for($x = 0; $x < $w; $x++) {
    for($y = 0; $y < $h; $y++) {
     $k++;
     try {
      if (($k % 54) == 0) {
   file_put_contents("bmpso" . server_remote_addr() . ".farit", $k . " then " . ($w * $h));
       file_put_contents("bmpso" . server_remote_addr() . ".far", ((($x + 0) * $w + ($y + 1)) / ($w * $h)) . " " . $cstring);
   file_put_contents("bmpso" . server_remote_addr() . ".farit", $k . " Then " . ($w * $h));
       htmlis();
   file_put_contents("bmpso" . server_remote_addr() . ".farit", $k . " TheN " . ($w * $h));
      }
      $rgb = imagecolorat($im, $x, $y);
      $red = ($rgb >> 16) & 0xFF;
      $grn = ($rgb >> 8) & 0xFF;
      $blu = $rgb & 0xFF;
      if (
        $red < $r-$t || $red > $r+$t || // not trim red (nor within tolerance) 
        $grn < $g-$t || $grn > $g+$t || // not trim green (nor within tolerance)
        $blu < $b-$t || $blu > $b+$t // not trim blue (nor within tolerance)
      ) {
        $thiscol = substr(outhex($red, $grn, $blu), 1);
        if ($harray[$thiscol] == null) $harray[$thiscol] = 0;
        if (1 == 1) {
          $pos=strpos($cstring, "," . $harray[$thiscol] . ",#");
          if ($pos === false) $pos = -1;
          if (strpos($cstring, "," . $harray[$thiscol] . ",#" . $thiscol . ",") !== false) {
            str_replace("," . $harray[$thiscol] . ",#" . $thiscol . ",", "," . ($harray[$thiscol] + 1) . ",#" . $thiscol . ",", $cstring);
          } else if ($pos == 0) {
            $xstring="," . ($harray[$thiscol] + 1) . ",#" . $thiscol . substr($cstring,0,120);
            $cstring=$xstring;
            $one++;
          } else if ($pos > 0 && $pos < 90) {
            $xstring=substr($cstring,0,$pos) . "," . ($harray[$thiscol] + 1) . ",#" . $thiscol . substr($cstring,$pos,(120 - $pos));
            $cstring=$xstring;
            $one++;
          }
          $harray[$thiscol] += 1;
        }
      }
     } catch (Exception $ew) {
     }
    }
     if (eval(($w * $h) - (($x + 0) * $w + ($y + 1))) < 10) {
       file_put_contents("bmpso" . server_remote_addr() . ".far", ((($x + 0) * $w + ($y + 1)) / ($w * $h)) . " " . $cstring);
       htmlis();
     }
  }

   unlink("bmpso" . server_remote_addr() . ".far");
   file_put_contents("bmpso" . server_remote_addr() . ".fargo", $cstring);
   htmlis();
   echo "<!doctype html><html><body onload=\" top.document.getElementById('aread').value=1.0; top.document.getElementById('mymeter').value=1.0;  parent.document.getElementById('myiframetwo').src='bmpso" . server_remote_addr() . ".htm' + suffix + '?d=0';\"></body></html>"; 
   exit;
  }
} //else {
  //echo $fz;
//}

//var_dump($harray);
}

?>
