<?
// image_average_colour.php
// RJM Programming - January, 2025
// Thanks to https://stackoverflow.com/questions/3468500/detect-overall-average-color-of-the-picture 

$verbose='';
$nump=0;
$avred=0;
$avgreen=0;
$avblue=0;
$avhash='';
$medred=0;
$medgreen=0;
$medblue=0;
$medcol='';
$medhash='';
$aimg="<a id=aform href='#top'>Back to report ...</a>&nbsp;&nbsp;<a onclick=\"if (document.getElementById('aimg')) { document.getElementById('aid').click();  }\" id=bform href='#aimg'>Back to image ...</a>";

function colourPalette($imageFile, $numColors, $granularity = 1) { // used to be 5 
   global $verbose, $avred, $avgreen, $avblue, $nump, $avhash, $medcol;
   $granularity = max(1, abs((int)$granularity)); 
   $colors = array(); 
   $size = @getimagesize($imageFile); 
   if($size === false) 
   { 
      user_error("Unable to get image size data"); 
      return false; 
   } 
   if (strpos(strtolower(str_replace('image/jp','image.jp',$imageFile)), ".jp") !== false) {
   $img = @imagecreatefromjpeg($imageFile);
   } else if (strpos(strtolower(str_replace('image/pn','image.pn',$imageFile)), ".png") !== false) {
   $img = @imagecreatefrompng($imageFile);
   } else if (strpos(strtolower(str_replace('image/gif','image.gif',$imageFile)), ".gif") !== false) {
   $img = @imagecreatefromgif($imageFile);
   } else if (strpos(strtolower(str_replace('image/web','image.web',$imageFile)), ".web") !== false) {
   $img = @imagecreatefromwebp($imageFile);
   } else if (strpos(strtolower(str_replace('image/gd','image.gd',$imageFile)), ".gd") !== false) {
   $img = @imagecreatefromgd($imageFile);
   } else {
   $img = @imagecreatefromstring(file_get_contents($imageFile)); 
   }
   // Andres mentioned in the comments the above line only loads jpegs, 
   // and suggests that to load any file type you can use this:
   // $img = @imagecreatefromstring(file_get_contents($imageFile)); 

   if(!$img) 
   { 
      user_error("Unable to open image file"); 
      return false; 
   } 
   for($x = 0; $x < $size[0]; $x += $granularity) 
   { 
      for($y = 0; $y < $size[1]; $y += $granularity) 
      { 
         $thisColor = imagecolorat($img, $x, $y); 
         $rgb = imagecolorsforindex($img, $thisColor);
         $avred = ($rgb['red'] + ($avred * $nump)) / ($nump + 1);
         $avgreen = ($rgb['green'] + ($avgreen * $nump)) / ($nump + 1);
         $avblue = ($rgb['blue'] + ($avblue * $nump)) / ($nump + 1);
         $nump++;
         $red = round(round(($rgb['red'] / 0x33)) * 0x33); 
         $green = round(round(($rgb['green'] / 0x33)) * 0x33); 
         $blue = round(round(($rgb['blue'] / 0x33)) * 0x33); 
         $thisRGB = sprintf('%02X%02X%02X', $red, $green, $blue); 
         if(array_key_exists($thisRGB, $colors)) 
         { 
            $colors[$thisRGB]++; 
         } 
         else 
         { 
            $colors[$thisRGB] = 1; 
         } 
      } 
   } 
   ob_start();
   var_dump($colors);
   $verbose=ob_get_contents();
   ob_end_clean();
   $avhash = sprintf('#%02X%02X%02X', (((round($avred) / 0x33)) * 0x33), (((round($avgreen) / 0x33)) * 0x33), (((round($avblue) / 0x33)) * 0x33)); 
   arsort($colors);
   $tot=0;
   $tsum=sizeof($colors);
   $tmed=(($tsum - ($tsum % 2)) / 2); 
   foreach (array_keys($colors) as $color) { 
     $freq=explode(')', explode(' int(', explode($color . ']', str_replace('"','',$verbose))[1])[1])[0];
     $tsum+=$freq;
     if ($tsum >= $tmed && $medcol == '') {
        $medcol='#' . $color;
        return array_slice(array_keys($colors), 0, $numColors); 
     }
   }
   return array_slice(array_keys($colors), 0, $numColors); 
} 


 function getAverage($sourceURL) {
    $image = imagecreatefromjpeg($sourceURL);
    $scaled = imagescale($image, 1, 1, IMG_BICUBIC); 
    $index = imagecolorat($scaled, 0, 0);
    $rgb = imagecolorsforindex($scaled, $index); 
    $red = round(round(($rgb['red'] / 0x33)) * 0x33); 
    $green = round(round(($rgb['green'] / 0x33)) * 0x33); 
    $blue = round(round(($rgb['blue'] / 0x33)) * 0x33); 
    return sprintf('#%02X%02X%02X', $red, $green, $blue); 
 }

 // array(105) { [666699]=> int(851) ["CC0033"]=> int(2) [330000]=> int(23) ["CCCCCC"]=> int(3233) ["CC9999"]=> int(12) ["CC99CC"]=> int(7)
 $hprefix="<html><head><scr" . "ipt type=text/javascript>
 
 function yesthreethree(indatauri) {
  document.getElementById('resultout').value=indatauri;
 }
 
 function checkit(iois) {
  if (iois != null) {
    aconto = (iois.contentWindow || iois.contentDocument);
    if (aconto != null) {
       if (aconto.document) { aconto = aconto.document; }
       if (aconto.body != null) {
        aconto.body.style.backgroundColor='transparent';
        aconto.getElementsByTagName('h1')[0].style.visibility='hidden';
        aconto.getElementsByTagName('h3')[0].style.visibility='hidden';
       }
    }
  }
 }

 
 </scr" . "ipt></head><body>";
 $imgcont='';
 $eleven=11;
 $midel=5;
 $modalt=' title="Modal colour"';
 $bdr='border:1px solid black;';
 if (isset($_GET['imageurl'])) {
   $imgcont=urldecode($_GET['imageurl']); 
 } else if (isset($_POST['imageurl'])) {
   $imgcont=urldecode($_POST['imageurl']);
 } else {
   $aimg='';
 }
 $hsuffix="<br><span id=sform></span><br>" . $aimg . "<br><br><form id=myform method=POST action=./image_average_colour.php><textarea name=imageurl id=resultout title='Image URL or data URI can go here ...' placeholder='Image URL or data URI can go here ...' style=width:90%;height:200px;></textarea><br><br><input name=num id=num type=text title='Top number of colours to report on ...' placeholder='Top number of colours to report on ...' value=11></input><br><br><br><input style='background-color:lightgreen;' type=submit value=Report></input>&nbsp;&nbsp;<iframe title='Select one video and one audio.' onload=checkit(this); scrolling=no frameborder=0 id=cbi data-type=file data-value=inv.mp4 data-accept=video/*audio/* src='/HTMLCSS/client_browsing.htm?numhastobe=1&typehastobe=image&rand=" . rand(0,18967564) . "' style='display:inline-block;width:173px;height:218px;margin-top:-204px;overflow:hidden;background-color:transparent;'></iframe></form></body></html>";
 if (isset($_GET['num'])) {
   $eleven=urldecode($_GET['num']); 
 } else if (isset($_POST['num'])) {
   $eleven=urldecode($_POST['num']);
 }
 $midel=(($eleven - ($eleven % 2)) / 2);
 $jimg=str_replace('+',' ',$imgcont);
 if (strpos(('~' . $imgcont), '~data:') !== false) {
   $xx='' . rand(0,34567);
   file_put_contents('/tmp/mytmpimg_' . $xx . '.' . explode(',', explode(';', explode('image/', $imgcont)[1])[0])[0], base64_decode(str_replace(' ','+',explode('base64,', $imgcont)[1])));
   $jimg='/tmp/mytmpimg_' . $xx . '.' . explode(',', explode(';', explode('image/', $imgcont)[1])[0])[0];
   $palette = colourPalette('/tmp/mytmpimg_' . $xx . '.' . explode(',', explode(';', explode('image/', $imgcont)[1])[0])[0], $eleven);
   unlink('/tmp/mytmpimg_' . $xx . '.' . explode(',', explode(';', explode('image/', $imgcont)[1])[0])[0]);
echo $hprefix . "<table id=top border=1 style='text-shadow:-1px 1px 1px #ff2d95;width:100%;background:linear-gradient(rgba(255,255,255,0.7),rgba(255,255,255,0.7)),URL(" . str_replace(' ','+',$imgcont) . ");background-repeat:no-repeat;background-size:contain;'><tr><th colspan=3>Image Colour Report<br>RJM Programming - January, 2025<br>Thanks to <a target=_blank title='https://stackoverflow.com/questions/3468500/detect-overall-average-color-of-the-picture' href='//stackoverflow.com/questions/3468500/detect-overall-average-color-of-the-picture'>https://stackoverflow.com/questions/3468500/detect-overall-average-color-of-the-picture</a></th></tr><tr><th onclick=alert(this.title); title='Median colour is " . $medcol . "' style='border-right:1px dashed olive;background-color:" . $medcol . "'></th><th colspan=2><a id=aid onclick=\"document.getElementById('myimg').style.display='block';\" title='Display below.' href='#aimg'>" . $jimg . "</a></th></tr><tr><th onclick=alert(this.title); title='Average colour is " . $avhash . " or rgb(" . round($avred) . "," . round($avgreen) . "," . round($avblue) . ")' style='border-right:1px dashed olive;background-color:rgb(" . round($avred) . "," . round($avgreen) . "," . round($avblue) . ");'></th><th>Colour</th><th>Frequency of Top " . $eleven . "</th></tr>\n"; 
foreach ($palette as $color) { 
   $freq=explode(')', explode(' int(', explode($color . ']', str_replace('"','',$verbose))[1])[1])[0];
   if ($modalt != '') { $modalt=str_replace(' colour"', ' colour is #' . $color . '" onclick=alert(this.title); ' . $color, $modalt); $bdr.='border-right:1px dotted yeelow;';   }
   echo "<tr><td style='" . $bdr . ";background-color:#$color;width:2em;'" . $modalt . ">&nbsp;</td><td>#$color</td><td>" . $freq . "</td></tr>\n"; 
   $modalt="";
   $bdr='border:1px solid black;';
} 
echo "</table><br><a id=aimg href='#top'>Back to report ...</a>&nbsp;&nbsp;<a id=aform href='#sform'>Back to form ...</a><br><img id=myimg style=display:none; src='" . str_replace(' ','+',$imgcont) . "'></img>\n" . $hsuffix;
 } else if ($imgcont != '') {
   $palette = colourPalette(str_replace('+',' ',$imgcont), $eleven);
echo $hprefix . "<table id=top border=1 style='text-shadow:-1px 1px 1px #ff2d95;width:100%;background:linear-gradient(rgba(255,255,255,0.7),rgba(255,255,255,0.7)),URL(" . str_replace('+',' ',$imgcont) . ");background-repeat:no-repeat;background-size:contain;'><tr><th colspan=3>Image Colour Report<br>RJM Programming - January, 2025<br>Thanks to <a target=_blank title='https://stackoverflow.com/questions/3468500/detect-overall-average-color-of-the-picture' href='//stackoverflow.com/questions/3468500/detect-overall-average-color-of-the-picture'>https://stackoverflow.com/questions/3468500/detect-overall-average-color-of-the-picture</a></th></tr><tr><th onclick=alert(this.title); title='Median colour is " . $medcol . "' style='border-right:1px dashed olive;background-color:" . $medcol . "'></th><th colspan=2><a id=aid onclick=\"document.getElementById('myimg').style.display='block';\" title='Display below.' href='#aimg'>" . $jimg . "</a></th><tr><th onclick=alert(this.title); title='Average colour is " . $avhash . " or rgb(" . round($avred) . "," . round($avgreen) . "," . round($avblue) . ")' style='border-right:1px dashed olive;background-color:rgb(" . round($avred) . "," . round($avgreen) . "," . round($avblue) . ");'></th><th>Colour</th><th>Frequency of Top " . $eleven . "</th></tr>\n"; 
foreach($palette as $color) { 
   $freq=explode(')', explode(' int(', explode($color . ']', str_replace('"','',$verbose))[1])[1])[0];
   if ($modalt != '') {  $modalt=str_replace(' colour"', ' colour is #' . $color . '" onclick=alert(this.title); ' . $color, $modalt); $bdr.='border-right:1px dotted yeelow;';  }
   echo "<tr><td style='" . $bdr . ";background-color:#$color;width:2em;'" . $modalt . ">&nbsp;</td><td>#$color</td><td>" . $freq . "</td></tr>\n"; 
   $modalt="";
   $bdr='border:1px solid black;';
} 
echo "</table><br><a id=aimg href='#top'>Back to report ...</a>&nbsp;&nbsp;<a id=aform href='#sform'>Back to form ...</a><br><img id=myimg style=display:none; src='" . str_replace('https:','',str_replace('http:','',str_replace('+',' ',$imgcont))) . "'></img>\n" . $hsuffix;
 } else {
 echo $hprefix . "<h1>Image Colour Report<h1><br><h3>RJM Programming - January, 2025</h3><br><h4>Thanks to <a target=_blank title='https://stackoverflow.com/questions/3468500/detect-overall-average-color-of-the-picture' href='//stackoverflow.com/questions/3468500/detect-overall-average-color-of-the-picture'>https://stackoverflow.com/questions/3468500/detect-overall-average-color-of-the-picture</a></h4><br>" . $hsuffix;
 }
?>


