Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggregation Enquires Welcome

Example Interest Rates: Home Loan Variable: 2.54% (2.74%*) • Home Loan Fixed: 3.74% (3.8%*) • Fixed: 2.48% (2.94%*) • Variable: 2.54% (2.74%*) • Investment IO: 2.3% (3.76%*) • Investment PI: 2.04% (3.8%*)

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 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Washington)

  Want to have a chat?
 

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment