php Imagick Get the color value of picture RGB

  • 2021-07-10 19:00:06
  • OfStack

Many image sites will retrieve the main color values of images uploaded by users, and then search for related images by color.

Previously, according to the online method, the picture was scaled (or mosaic), then each pixel was traversed, and then the value with the most RGB times was counted. This method is too inefficient and the obtained RGB value is not accurate enough. After that, it was found that the quantizeImage method using Imagick can easily get the average RGB value in the picture.


$average = new Imagick("xiaocai.jpg");
$average->quantizeImage( 10, Imagick::COLORSPACE_RGB, 0, false, false );
$average->uniqueImageColors();
function GetImagesColor( Imagick $im ){
$colorarr = array();
$it = $im->getPixelIterator();
$it->resetIterator();
while( $row = $it->getNextIteratorRow() ){
foreach ( $row as $pixel ){
// www.ofstack.com
$colorarr[] = $pixel->getColor();
}
}
return $colorarr;
}
$colorarr = GetImagesColor($average);
foreach($colorarr as $val){
echo "<div style='background-color: rgb({$val['r']},{$val['g']},{$val['b']});width:50px;height:50px;float:left;'></div>";
}


Related articles: