Skip to content

Instantly share code, notes, and snippets.

@etelford
Last active February 2, 2017 20:00
Show Gist options
  • Save etelford/ca45806f5ee01c0ff8ee to your computer and use it in GitHub Desktop.
Save etelford/ca45806f5ee01c0ff8ee to your computer and use it in GitHub Desktop.
Get the most common color from an image using the PHP Intervention library
<?php
use Intervention\Image\Filters\FilterInterface;
/**
* A simple filter to get the predominant color from an image using the
* Intervention library (http://image.intervention.io).
*
* Usage with no options:
* $image = Image::make($file);
* $primaryColor = $image->filter(new PrimaryColor());
*
* Usage with options:
* $image = Image::make($file);
* $filter = new PrimaryColor();
* $primaryColor = $image->filter($filter->format('hex')
* ->ignores(['#ffffff']));
*/
class PrimaryColor implements FilterInterface
{
/**
* The color format to return
*
* @var string
*/
protected $format = 'hex';
/**
* Colors to ignore
*
* @var array
*/
protected $ignores = [
'#ffffff',
'#000000'
];
/**
* Applies filter effects to given image
*
* @param \Intervention\Image\Image $image
* @return array
*/
public function applyFilter(\Intervention\Image\Image $image)
{
foreach (range(0, $image->height() - 1) as $y) {
foreach (range(0, $image->width() - 1) as $x) {
$color = $image->pickColor($x, $y, $this->format);
if (isset($occurrences[$color])) {
$occurrences[$color]++;
} else {
$occurrences[$color] = 1;
}
}
}
arsort($occurrences);
$this->removeIgnoredColors($occurrences);
return key($occurrences);
}
/**
* Remove all the ignored colors from the results
*
* @param array &$occurrences
* @return void
*/
protected function removeIgnoredColors(&$occurrences)
{
foreach ($this->ignores as $color) {
unset($occurrences[$color]);
}
}
/**
* Set the colors to ignore
*
* @param array $colors
* @return $this
*/
public function ignores(array $colors)
{
$this->ignores = $colors;
return $this;
}
/**
* Set the color format
*
* @param string $format
* @return $this
*/
public function format($format)
{
$this->format = $format;
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment