如何知道图像中存在多少种颜色?

问题描述:

<?php
$img=imagecreatefrompng('dense.png');
list($width, $height)=getimagesize('dense.png'); 
$t=0;
for( $i=0 ; $i<$height ; $i++ )
{
    for( $j=0 ; $j<$width ; $j++ )
    {
        $pix  = imagecolorat($img, $i, $j);
        $cols = imagecolorsforindex($img, $pix);
        $r = $cols['red'];
        $g = $cols['green'];
        $b = $cols['blue'];
        $pixel[$i][$j][0]=$r;
        $pixel[$i][$j][1]=$g;
        $pixel[$i][$j][2]=$b;       
        }
}

for( $i=0 ; $i<$height ; $i++ )
{
    for( $j=0 ; $j<$width ; $j++ )
    {
        echo "(".$i.",".$j.") color of that pixel is (".$pixelcolor[$i][$j][0].",".$pixelcolor[$i][$j][1].",".$pixelcolor[$i][$j][2].").</p>";
    }
    echo"<br/>";
}
?>

This is the my code but when i run this code its give me blank webpage.

I want to make one array which store the rgb value of each pixel and it also print on the webpage and reduce those value which are repeating in the array.

so i want to know that how many colors are exist in the images?

Your code is probably dying from a memory exhaustion error. Creating a million or so arrays can cause that. Here's a script that counts the number of unique colors in an image in a fairly efficient manner (for PHP):

<?php

$path = "test.jpg";

$img = imagecreatefromjpeg($path);
$w = imagesx($img);
$h = imagesy($img);

// capture the raw data of the image
ob_start();
imagegd2($img, null, $w);
$data = ob_get_clean();
$totalLength = strlen($data);

// calculate the length of the actual pixel data
// from that we can derive the header size
$pixelDataLength = $w * $h * 4;
$headerLength = $totalLength - $pixelDataLength;

// use each four-byte segment as the key to a hash table
$counts = array();
for($i = $headerLength; $i < $totalLength; $i += 4) {
    $pixel = substr($data, $i, 4);
    $count =& $counts[$pixel];
    $count += 1;
}
$colorCount = count($counts);
echo $colorCount;

?>

$colorCount is the number of unique colors in the image. $counts gives you the number of times each color occurs. Each $key is a 4-byte string. The first byte is transparency. A value of zero means opaque. The second, third, and fourth bytes are R, G, and B respectively. You'll need to call ord() to get the value.

You can get total number of colors in an image using imagecolorstotal() function

 <?php
    // Create image instance
    $im = imagecreatefromgif('php.gif');

    echo 'Total colors in image: ' . imagecolorstotal($im);

    // Free image
    imagedestroy($im);
 ?>

http://php.net/manual/en/function.imagecolorstotal.php