Skip to content

Instantly share code, notes, and snippets.

@ncou
Created September 5, 2016 22:33
Show Gist options
  • Save ncou/079ddb9f31bd80cf387f13c8a6bd9bc9 to your computer and use it in GitHub Desktop.
Save ncou/079ddb9f31bd80cf387f13c8a6bd9bc9 to your computer and use it in GitHub Desktop.
PHP: Determine the dominant color of an image
<?php
/**
* PHP: Determine the dominant color of an image
* http://www.catswhocode.com/blog/10-super-useful-php-snippets-you-probably-havent-seen
*/
$i = imagecreatefromjpeg("image.jpg");
for ($x=0;$x<imagesx($i);$x++) {
for ($y=0;$y<imagesy($i);$y++) {
$rgb = imagecolorat($i,$x,$y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> & 0xFF;
$b = $rgb & 0xFF;
$rTotal += $r;
$gTotal += $g;
$bTotal += $b;
$total++;
}
}
$rAverage = round($rTotal/$total);
$gAverage = round($gTotal/$total);
$bAverage = round($bTotal/$total);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment