Introduction to how to get the main color of an image in PHP

巴扎黑
Release: 2023-03-14 17:38:02
Original
1997 people have browsed it

This article mainly introduces the method of obtaining the main color of the picture through PHP programming. The Imagick extension based on PHP implements the function of obtaining the color value of the picture. Friends in need can refer to the following

This article describes PHP with examples Programmatically obtain the main color of an image. Share it with everyone for your reference, the details are as follows:

The code uses the image extension of PHP, so before using it, you need to install the Imagick extension of PHP. The specific installation is as follows (under windows): Installing PHP under windows7 Imagick and imagemagick extension tutorial

The code is as follows:


<?php
$average = new Imagick("./fruit/143511081321676_593.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 ){
      $colorarr[] = $pixel->getColor();
    }
  }
  return $colorarr;
}
$colorarr = GetImagesColor($average);
foreach($colorarr as $val){
  $r += $val[&#39;r&#39;];
  $g += $val[&#39;g&#39;];
  $b += $val[&#39;b&#39;];
  echo "<p style=&#39;background-color: rgb({$val[&#39;r&#39;]},{$val[&#39;g&#39;]},{$val[&#39;b&#39;]});width:50px;height:50px;float:left;&#39;></p>";
}
$r = round($r/10);
$g = round($g/10);
$b = round($b/10);
echo "<br><p style=&#39;background-color: rgb({$r},{$g},{$b});width:100px;height:100px;float:left;&#39;></p>";
?>
Copy after login

The above is the detailed content of Introduction to how to get the main color of an image in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template