Method of Obtaining Color Value of Picture by PHP

  • 2021-07-07 06:41:06
  • OfStack

This example describes the method of obtaining picture color value by PHP. PHP obtains picture color value and detects the main color of picture by reading picture by imagecreatefromjpeg function, and then obtaining each color value by recycling.

The specific code is as follows:


<?php
$i=imagecreatefromjpeg("photo3.jpg");// Test pictures, define yourself 1 Pay attention to the path 
for ($x=0;$x<imagesx($i);$x++) {
  for ($y=0;$y<imagesy($i);$y++) {
    $rgb = imagecolorat($i,$x,$y);
    $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);
// Example: 
echo $rAverage;
?>

Related articles: