Skip to content

Instantly share code, notes, and snippets.

@arguiot
Last active September 2, 2016 12:10
Show Gist options
  • Save arguiot/45a7978c48fb6c7e478a0dce314d5b76 to your computer and use it in GitHub Desktop.
Save arguiot/45a7978c48fb6c7e478a0dce314d5b76 to your computer and use it in GitHub Desktop.
image color average using PHP
//I made a function that calculates the average color of a given image resource and returns it in "#rrggbb" format (hex):
function average($img) {
$w = imagesx($img);
$h = imagesy($img);
$r = $g = $b = 0;
for($y = 0; $y < $h; $y++) {
for($x = 0; $x < $w; $x++) {
$rgb = imagecolorat($img, $x, $y);
$r += $rgb >> 16;
$g += $rgb >> 8 & 255;
$b += $rgb & 255;
}
}
$pxls = $w * $h;
$r = dechex(round($r / $pxls));
$g = dechex(round($g / $pxls));
$b = dechex(round($b / $pxls));
if(strlen($r) < 2) {
$r = 0 . $r;
}
if(strlen($g) < 2) {
$g = 0 . $g;
}
if(strlen($b) < 2) {
$b = 0 . $b;
}
return "#" . $r . $g . $b;
}
//Although, I've noticed that you can also get a fairly good average color generating a 1px by 1px copy with imagecopyresampled (the //pixel generated is colored with the average color).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment