marceloxp
10/4/2013 - 9:34 PM

PHP Color Average

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);
		}