T
T
TekVanDo2014-01-10 12:43:32
PHP
TekVanDo, 2014-01-10 12:43:32

What's the easiest way to get an array of colors from an image?

What is the best library to use? And if possible the algorithm.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2014-01-10
@CTAKAH4uK

www.php.net/manual/en/function.imagecolorat.php

$w = imagesx($image);
$h = imagesy($image);

$colors = array();

for ($x = 0; $x <= $w; $x++) {
  $colors[$x] = array();
   	 for ($y = 0;$y <= $h; $y++ ) {
    $color = imagecolorat($img, $x, $y);
   		$red = ($rgb >> 16) & 0xFF;
  		$green = ($rgb >> 8) & 0xFF;
    $blue = $rgb & 0xFF;
    $colors[$x][$y] = $color;
  }
}

I
Igor Golovanov, 2014-01-10
@golovanov

Need to get all or N-most used colors?
The most used can be obtained like this

// The original image is the average colors
$im = new Imagick( "test.png" );

// Reduce the amount of colors to 10
$im->quantizeImage( 10, Imagick::COLORSPACE_RGB, 0, false, false );

// Only save one pixel of each color
$im->uniqueImageColors();

// Get ImagickPixelIterator
$it = $im->getPixelIterator();

// Reset the iterator to begin
$it->resetIterator();

// palette
$palette = array();

// Loop trough rows
while ($row = $it->getNextIteratorRow()) {
    // Loop trough columns
    foreach ($row as $pixel) {
        $color = $pixel->getColor();
        foreach (array('r', 'g', 'b') as $channel) {
            $color[$channel] = dechex($color[$channel]);
            if (strlen($color[$channel]) != 2) {
                $color[$channel] = '0' . $color[$channel];
            }
        }
        $palette[] = $color['r'] . $color['g'] . $color['b'];
    }
}

// print palette
print_r($palette);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question