[PHP]识别图片主色调
一、适用情景:,根据颜色列出相应图片。
二、主程序及API解释:
[php]
<?php
class MajorColor
{
//参考颜色
protected $_colors = null;
//容差
protected $_tolerance = 80;
//忽略的颜色
protected $_ignoreColors = array();
//支持的图片类型
protected $_funcs = array('image/png' => 'imagecreatefrompng', 'image/jpeg' => 'imagecreatefromjpeg', 'image/gif' => 'imagecreatefromgif');
public function __construct(array $colors = null) {
if(null !== $colors) {
$this->_colors = $colors;
}
}
public function setColors(array $colors) {
$this->_colors = $colors;
}
public function setTolerance($tolerance) {
$this->_tolerance = $tolerance;
}
public function setIgnoreColors($colors) {
$this->_ignoreColors = $colors;
}
public function _isValidColor($confVal, $val) {
if(is_array($confVal)) {
return $val >= $confVal[0] && $val <= $confVal[1];
} else {
return $val >= $confVal - $this->_tolerance && $val <= $confVal + $this->_tolerance;
}
}
public function getOrderedColors($pic) {
$size = getimagesize($pic);
if(!$size) {
return false;
}
$width = $size[0];
$height = $size[1];
$mime = $size['mime'];
$func = isset($this->_funcs[$mime]) ? $this->_funcs[$mime] : null;
if(!$func) {
return false;
}
$im = $func($pic);
if(!$im) {
return false;
}
$total = $width * $height;
$nums = array();
for($i = 0; $i < $width; $i++) {
for($m = 0; $m < $height; $m++) {
$color_index = imagecolorat($im, $i, $m);
$color_tran = imagecolorsforindex($im, $color_index);
$alpha = $color_tran['alpha'];
unset($color_tran['alpha']);
if(100 < $alpha || in_array($color_tran, $this->_ignoreColors)) {
continue;
}
foreach ($this->_colors as $colorid => $color) {
if($this->_isValidColor($color['red'], $color_tran['red'])
&& $this->_isValidColor($color['green'], $color_tran['green'])
&& $this->_isValidColor($color['blue'], $color_tran['blue'])
) {
$nums[$colorid] = isset($nums[$colorid]) ? $nums[$colorid] + 1 : 1;
}
}
}
}
imagedestroy($im);
arsort($nums);
return $nums;
}
public function getMajorColor($pic) {
$nums = $this->getOrderedColors($pic);
$keys = array_keys($nums);
return $keys[0];
}
}
1.void setColors(array $colors)
设置可选颜色,即上图中“全部颜色”下的所有颜色(白、灰、黑...)
2.void setTolerance(int $tolerance)
设置容差,比如绿色的RGB值为(0,255,0),如果设置容差为40,那么-40<=R<
补充:Web开发 , php ,