Two ways to get Image color values in PHP

Source: Internet
Author: User

Two ways to get Image color values in PHP

    1. <?php$i=imagecreatefromjpeg ("photo3.jpg");//test picture 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 >> & Amp 0xFF, $b = $rgb & 0xFF, $rTotal + = $r, $gTotal + = $g, $bTotal + = $b, $total + +;}} $rAverage = Round ($rTotal/$total); $gAverage = round ($gTotal/$total); $bAverage = round ($bTotal/$total);//Example: Echo $ Raverage;? >

Example 2,php gets the image primary RGB color value. Retrieves the primary color value of the image based on the image uploaded by the user, and then searches the relevant image by color.


The image is scaled (or mosaic) on the web and then traversed by each pixel, and then the most RGB values are counted, which is too inefficient and the RGB values taken are not accurate enough. It was later found that the Quantizeimage method using Imagick can easily fetch the average RGB value in the image. (bbs.it-home.org Script Academy)

Code:

Php$average = new Imagick ("xiaocai.jpg"); $average->quantizeimage (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.orgreturn $colorarr;} $colorarr = Getimagescolor ($average); foreach ($colorarr as $val) {echo "";}

Output Result:


  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.