RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.69% (5.89%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.69% (5.89%*) • Investment IO: 5.74% (6.40%*) • Investment PI: 5.49% (6.27%*)

# Determine the Dominant Color of an Image With PHP

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
\$i = imagecreatefromjpeg(\$image);
11

12
for (\$x=0;\$x<imagesx(\$i);\$x++) {
13
for (\$y=0;\$y<imagesy(\$i);\$y++) {
14
\$rgb = imagecolorat(\$i,\$x,\$y);
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
\$r = round(\$r_total / \$total);
25
\$g = round(\$g_total / \$total);
26
\$b = round(\$b_total / \$total);
27

28
\$rgb = (\$array) ? array('r'=> \$r, 'g'=> \$g, 'b'=> \$b) : sprintf(\$format, \$r, \$g, \$b);
29

30
return \$rgb;
31
}
32

33
/* Usage */
34
\$image = 'image.jpg';
35
echo beliefmedia_dominant_color(\$image);

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

Want to have a chat?