Home > Backend Development > PHP Tutorial > Two ways to get the color value of an image in php

Two ways to get the color value of an image in php

PHP中文网
Release: 2016-07-25 08:52:59
Original
2405 people have browsed it

Two ways for php to get the color value of an image

  1. <?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.


Two ways to get the color value of an image in php

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:

Two ways to get the color value of an image in php





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