RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts</strong | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.69% (5.89%*) • Home Loan Fixed: 5.39% (6.59%*) • Fixed: 5.39% (6.59%*) • Variable: 5.69% (5.89%*) • Investment IO: 5.69% (6.48%*) • Investment PI: 5.39% (6.59%*)

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: 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 complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment