Two ways to get the color value of an image in php
Release: 2016-07-25 08:52:59
Original
2476 people have browsed it
Two ways for php to get the color value of an image
<?php
$i=imagecreatefromjpeg("photo3.jpg");//测试图片
for ($x=0;$x<imagesx($i);$x++) {
for ($y=0;$y<imagesy($i);$y++) {
$rgb = imagecolorat($i,$x,$y);
$r=($rgb >>16) & 0xFF;
$r=($rgb >>16) & 0xFF;
$g=($rgb >> & 0xFF;
$b=$rgb & 0xFF;
$rTotal += $r;
$gTotal += $g;
$bTotal += $b;
$total++;
}
}
$rAverage = round($rTotal/$total);
$gAverage = round($gTotal/$total);
$bAverage = round($bTotal/$total);
//示例:
echo $rAverage;
?> Copy after login
Example 2, php gets the main RGB color value of an image.
Retrieve the main color value of the image based on the image uploaded by the user, and then search for related images by color.

Follow the online method to scale (or mosaic) the image and then traverse each pixel, and then count the value with the most RGB times. This method is too inefficient and the RGB value obtained is not accurate enough.
Later I discovered that using Imagick's quantizeImage method can easily get the average RGB value in the picture. (bbs.it-home.org Scripting School) Code: ?php
$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 ){
$colorarr[] = $pixel->getColor();
}
} // bbs.it-home.org
return $colorarr;
}
$colorarr = GetImagesColor($average);
foreach($colorarr as $val){
echo "
";
} Copy after login Output result:

|
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
Latest Articles by Author
-
2024-12-12 11:03:15
-
2024-12-12 11:01:15
-
2024-12-12 10:59:13
-
2024-12-12 10:58:16
-
2024-12-12 10:57:14
-
2024-12-12 10:56:12
-
2024-12-12 10:55:13
-
2024-12-12 10:54:17
-
2024-12-12 10:53:16
-
2024-12-12 10:51:16
Latest Issues
-
2025-03-21 13:39:34
-
2025-03-21 13:38:34
-
2025-03-21 13:37:19
-
2025-03-21 13:35:24
-
2025-03-21 13:34:32