DETERMINE THE DOMINANT COLOR OF AN IMAGE IN PHP

This code will be useful for  images or photography website. With it, you can analyze any image and get its dominant color (R, G, or B).

 

$i = imagecreatefromjpeg("image.jpg");

for ($x=0;$x<imagesx($i);$x++) {
    for ($y=0;$y<imagesy($i);$y++) {
        $rgb = imagecolorat($i,$x,$y);
        $red   = ($rgb >> 16) & 0xFF;
        $green   = ($rgb >>  & 0xFF;
        $blue   = $rgb & 0xFF;

        $redTotal += $red;
        $greenTotal += $green;
        $blueTotal += $blue;
        $total++;
    }
}

$redAverage = round($redTotal/$total);
$greenAverage = round($greenTotal/$total);
$blueAverage = round($blueTotal/$total);