Last active
September 2, 2016 12:10
-
-
Save arguiot/45a7978c48fb6c7e478a0dce314d5b76 to your computer and use it in GitHub Desktop.
image color average using PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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