需要安装 php 的 imagick 扩展

1
2
3
4
5
6
7
8
9
10
$image = new \Imagick($file);   //$file 图片存储地址或者url地址
$image->quantizeImage(2, \Imagick::COLORSPACE_RGB, 0, false, false); // 这个里边的2表示获取2个较多的颜色,1的话就是1个主要色调
$image->uniqueImageColors();

$iter = $image->getPixelIterator();
$iter->resetIterator();
$row = $iter->getNextIteratorRow();
$color = $row[0]->getColor(); //获取到第一个颜色点的颜色

return $color;

刚开始用的时候,把quantizeImage的第一个参数填的是1,匹配出的颜色很淡

Imagick::quantizeImage ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError ) :
bool

  • $numColors:它指定颜色的数量。
  • $colorspace:它指定色彩空间。
  • $treeDepth:它指定树的深度。
  • $dither:它指定是否允许抖动。
  • $measureError:它指定是否测量图像差异误差。

返回值:

  • 成功时,此函数返回Gmagick对象。
  • 异常:此函数在错误时引发GmagickException。