The following PHP function will determine the dominant (average) color of an image with PHP. The result can be returned as either an array of formatted string. Other color functions can be found on our blog by way of the color tag.
1
<?php
2
/*
3
Determine dominant color of an image
4
http://www.beliefmedia.com/code/php-snippets/determine-dominant-color-image
5
*/
6
7
function beliefmedia_dominant_color($image, $array = false, $format = 'rgb(%d, %d, %d)') {
8
9
/* http://php.net/manual/en/function.imagecreatefromjpeg.php */
10
11
12
13
14
15
$r = ($rgb >> 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF;
16
17
$r_total += $r;
18
$g_total += $g;
19
$b_total += $b;
20
$total++;
21
}
22
}
23
24
25
26
27
28
29
30
return $rgb;
31
}
32
33
/* Usage */
34
$image = 'image.jpg';
35
echo beliefmedia_dominant_color($image);