Skip to content

Instantly share code, notes, and snippets.

@marceloxp
Created October 4, 2013 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marceloxp/6833163 to your computer and use it in GitHub Desktop.
Save marceloxp/6833163 to your computer and use it in GitHub Desktop.
PHP Color Average
public function colorAverage($rect)
{
//$rect = array(x, y, w, h);
$im = @imagecreatetruecolor($rect[2], $rect[3]);
if (!$im) { return false; }
imagecopy($im, $this->info, 0, 0, $rect[0], $rect[1], $rect[2], $rect[3]);
$imgW = $rect[2];
$imgH = $rect[3];
$tot = 0;
$rTot = 0;
$gTot = 0;
$bTot = 0;
for ($col = 0; $imgW > $col; $col++) {
// Loop through every row in the current column of the image.
for ($row = 0; $imgH > $row; $row++) {
// Get the index of the color of the current pixel.
$rgb = imagecolorat($im, $col, $row);
// Extract the RGB values into the total variables.
$rTot += (($rgb >> 16) & 0xFF);
$gTot += (($rgb >> 8) & 0xFF);
$bTot += ($rgb & 0xFF);
// Increase the total amount of pixles.
$tot++;
}
}
// Get the rounded average RGB variables.
$rAverage = round($rTot / $tot);
$gAverage = round($gTot / $tot);
$bAverage = round($bTot / $tot);
$background = imagecolorallocate($im, $rAverage, $gAverage, $bAverage);
imagefill($im,0,0,$background);
imagepng($im, "img/media.png");
return array($rAverage, $gAverage, $bAverage);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment