<?php
// image_colours_of.php
// RJM Programming
// November, 2018

$cnt=0;
$upload=false;
$style="";
$datau="";
$prefix="";
$suffix=" ";
$jsuffix=0;
$nhead="><h1>Image Colour Count</h1><h3>RJM Programming - November, 2018 ... thanks to <a target=_blank title='Great coding here, thanks' href='//stackoverflow.com/questions/25400805/how-to-know-howmany-colors-are-exist-in-the-image'>https://stackoverflow.com/questions/25400805/how-to-know-howmany-colors-are-exist-in-the-image</a></h3>";
$nform="<br><form action='./image_colours_of.php' method='POST'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input style='display:inline-block;' type='file' id='cimage' accept='image/*' multiple capture> or Image URL: <input style=width:50%; name='image' id='image' type='text' value=''></input>&nbsp;&nbsp;<input style=background-color:yellow; type='submit' value='Colours Count'></input><input type=hidden name=background value='yes'></input></form>";
$byes=false;
if (isset($_POST['background']) || isset($_GET['background'])) {
  $byes=true;
}

$jscr="<scri" . "pt type='text/javascript'>

var form=null;
var xhr=null;
var cnt=0;
var clicked=[];

var ourmimetype='';
var types = ['video/mp4','image/svg','audio/wav','audio/x-wav','audio/x-pn-realaudio','audio/x-mpegurl','audio/x-aiff','audio/mpeg','audio/mid',
      'audio/basic','audio/ogg','video/x-sgi-movie','video/x-msvideo','video/quicktime','audio/mp3','video/mp4','video/mpeg',
      'video/x-la-asf','video/ogg','video/webm','audio/mp4', 'image/jpeg', 'image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/tif',
      'text/html', 'text/html', 'text/html', 'text/javascript', 'text/css', 'text/plain', 'text/xml', 'text/csv',
      'application/vnd.ms-word', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/x-php', 'application/pdf',
      'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/vnd.ms-powerpoint',
      'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
var exts = ['.mp4','.svg','.wav','.wav','.ram','.m3u','.aiff','.mp3','.rmi',
      '.snd','.ogg','.movie','.avi','.mov','.mp3','.m4v','.mpeg',
      '.lsx','.ogv','.webm','.m4a', '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tif',
      '.htm', '.html', '.htmls', '.js', '.css', '.txt', '.xml', '.csv', 
      '.doc', '.docx', '.php', '.pdf',
      '.pptx', '.ppt',
      '.xls', '.xlsx'];

function onl() {
var input = document.getElementById('cimage'); // .querySelector('input[type=file]'); // .getElementById('cimage'); // see Example 4

input.onchange = function () {
  var file = input.files; //[0];
  for (var ii=0; ii<file.length; ii++) {
    if (ii == 0) { upload(file); }
  }
};
}

function upload(file) {
  var suffix='';
  clicked=[];
  form = new FormData(); 
  xhr = new XMLHttpRequest(); 
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      if (1 == 2) {
      var wo=window.open('','_blank','top=50,left=50,width=600,height=600');
      wo.document.write('<h' + '1' + this.responseText.split('</bo' + 'dy>')[0].split('<h' + '1')[1]);
      } else {
      document.body.innerHTML='<h' + '1' + this.responseText.split('</bo' + 'dy>')[0].split('<h' + '1')[1];
      }
    }
  };

  for (var i=0; i<file.length; i++) {
  clicked.push(false);
 ourmimetype='';
 for (var ji=0; ji<exts.length; ji++) {
      if (('.' + file[i].name.split('.')[eval(-1 + file[i].name.split('.').length)]).toLowerCase() == exts[ji].toLowerCase()) {
        ourmimetype=types[ji];
      }
 }
    form.append('filename' + suffix, file[i].name);
    form.append('types' + suffix, ourmimetype);
    form.append('images' + suffix, file[i]);
    suffix='' + eval(1 + i);
  }

  xhr.open('post', 'image_colours_of.php', true);
  xhr.setRequestHeader('Cache-Control', 'no-cache');
  xhr.send(form);
}

</scr" . "ipt>
";

while (("" . $suffix) != "") {
$suffix=trim($suffix);
if (isset($_POST['filename' . $suffix])) {
  if (!file_exists($_FILES['images' . $suffix]['tmp_name']) || !is_uploaded_file($_FILES['images' . $suffix]['tmp_name'])) {
  if (1 == 2) { file_put_contents('qpm.qpm','No upload'); }
  //echo '<html><body onload=" alert(' . "'" . 'No upload' . "'" . '); if (top.document.getElementById(' . "'" . 'demail' . "'" . ')) {   top.document.getElementById(' . "'" . 'demail' . "'" . ').innerHTML=' . "'" . 'No upload' . "';  } " . '"></body></html>';
  exit;
  }
  $upload=true;
  $fni=dirname(__FILE__) . "/" . str_replace("+", " ", urldecode($_POST['filename' . $suffix]));
  $ii=0;
  while (file_exists($fni)) {
              $fni=str_replace(".", "" . $ii . ".", $fni);
              $ii++;
  }
  move_uploaded_file($_FILES['images' . $suffix]['tmp_name'], $fni);
  $image = $fni;
  $datau="data:" . str_replace('+',' ',urldecode($_POST['types' . $suffix])) . ";base64," . base64_encode(file_get_contents($image));
  $style=" style='background:\"url(" . datau . ")\";'";
  if (("" . $suffix) == "") {
    $suffix=1;
    if (!isset($_POST['filename' . $suffix])) {  $suffix="";  }
  } else {
    $suffix++;
    if (!isset($_POST['filename' . $suffix])) {  $suffix="";  }
  }
  $jsuffix=$suffix;
} else if (isset($_GET['image'])) {
  $image = str_replace("+"," ",urldecode($_GET['image']));
} else if (isset($_POST['image'])) {
  $image = str_replace("+"," ",urldecode($_POST['image']));
} else {
  $image = ""; //"/Applications/MAMP/htdocs/clouds.jpg";
}

$x="";
$colourCount = 0;

if ($image != "") {
//if (1 == 2 && strpos(strtolower($image), ".jp") !== false) {
// $img = @imagecreatefromjpeg($image);
// $prefix="<p>" . $x . $image . " contains " . $colourCount . " colours.</p>";
//} else {
 $img = @imagecreatefromstring(file_get_contents($image));
//}

 if ($upload) {  unlink($image);   }

if (!$img) {
//$x = " error ";
$prefix.="<p>" . $x . $image . " contains " . $colourCount . " colours.</p>";
} else {
$colourCount = imagecolorstotal($img);

if ($colourCount == 0) { // with code below, thanks to https://stackoverflow.com/questions/25400805/how-to-know-howmany-colors-are-exist-in-the-image
//echo "yes";
//exit;
$w = imagesx($img);
$h = imagesy($img);

// capture the raw data of the image
ob_start();
imagegd2($img, null, $w);
$data = ob_get_clean();
$totalLength = strlen($data);

// calculate the length of the actual pixel data
// from that we can derive the header size
$pixelDataLength = $w * $h * 4;
$headerLength = $totalLength - $pixelDataLength;

// use each four-byte segment as the key to a hash table
$counts = array();
for($i = $headerLength; $i < $totalLength; $i += 4) {
    $pixel = substr($data, $i, 4);
    $count =& $counts[$pixel];
    $count += 1;
}
$colourCount = count($counts);
//echo $colourCount;
if ($byes) {
$nhead=str_replace("><h1", " style=\"background-image: linear-gradient(rgba(255,255,255,0.6),rgba(255,255,255,0.6)), url('" . $image . "'); background-repeat:repeat;\"><div style=background-color:rgba(255,255,255,0.7);><h1",$nhead);
$nform.="</div>";
if ($datau != "") {
$prefix.="<p><a style='text-decoration:underline;cursor:pointer;' onclick=\"document.body.style.backgroundImage='url(" . $datau . ")';\" title='New background image'>" . $image . "</a> contains " . $colourCount . " colours.</p><br><img onmouseout=\" if (!clicked[" . $jsuffix . "]) { document.getElementById('xidu" . $suffix . "').style.display='none'; }\" onmouseover=\"document.getElementById('xidu" . $suffix . "').style.display='inline-block';\" onclick=\"clicked[" . $jsuffix . "]=true; document.getElementById('xidu" . $suffix . "').style.display='inline-block';\" id=idu" . $suffix . " style='width:60px;display:inline-block;' src='" . $datau . "'></img><img id=xidu" . $suffix . " style='display:none;' src='" . $datau . "'></img><hr>";
} else {
$prefix.="<p><a target=_blank href='" . $image . "' title='New window'>" . $image . "</a> contains " . $colourCount . " colours.</p><br>"; //<img src='" . $image . "'></img>";
}
$byes=false;
} else {
if ($datau != "") {
$prefix.="<p><a style='text-decoration:underline;cursor:pointer;' onclick=\"document.body.style.backgroundImage='url(" . $datau . ")';\" title='New background image'>" . $image . "</a> contains " . $colourCount . " colours.</p><br><img onmouseout=\" if (!clicked[" . $jsuffix . "]) { document.getElementById('xidu" . $suffix . "').style.display='none'; }\" onmouseover=\"document.getElementById('xidu" . $suffix . "').style.display='inline-block';\" onclick=\"clicked[" . $jsuffix . "]=true; document.getElementById('xidu" . $suffix . "').style.display='inline-block';\" id=idu" . $suffix . " style='width:60px;display:inline-block;' src='" . $datau . "'></img><img id=xidu" . $suffix . " style='display:none;' src='" . $datau . "'></img><hr>";
} else {
$prefix.="<p><a target=_blank href='" . $image . "' title='New window'>" . $image . "</a> contains " . $colourCount . " colours.</p><br><img src='" . $image . "'></img>";
}
}
}

// Free image
imagedestroy($img);
}
}
}

echo "<!doctype html><html><head><title>Image Colour Count - RJM Programming - November, 2018 ... thanks to https://stackoverflow.com/questions/25400805/how-to-know-howmany-colors-are-exist-in-the-image</title>" . $jscr . "</head><body onload='onl();'" . $nhead . $prefix . $nform . "</body></html>";

?>
