imagecolorsforindex

(PHP 3, PHP 4, PHP 5)

imagecolorsforindex -- Get the colors for an index

Description

array imagecolorsforindex ( resource image, int index )

This returns an associative array with red, green, blue and alpha keys that contain the appropriate values for the specified color index.

Пример 1. imagecolorsforindex() example

<?php

// open an image
$im = imagecreatefrompng('nexen.png');

// get a color
$start_x = 40;
$start_y = 50;
$color_index = imagecolorat($im, $start_x, $start_y);

// make it human readable
$color_tran = imagecolorsforindex($im, $color_index);

// what is it ?
echo '<pre>';
print_r($color_tran);
echo
'</pre>';

?>

This example will output :

Array
(
    [red] => 226
    [green] => 222
    [blue] => 252
    [alpha] => 0
)

See also imagecolorat() and imagecolorexact().



imagecolorsforindex
adspeed.com
23-Aug-2005 04:05
To correct m4551 at abasoft dot it example:

ImageTrueColorToPalette($im,1,$t);

might give less colors than $t, so the for loop should call "$i<ImageColorsTotal($im)" instead of "$i<$t" just to be sure, or you'll get the warning: Color index [0-9] out of range
strozek(a)deas()harvard()edu
25-Jun-2004 01:32
Regarding m4551's method of conversion -- the actual CCIR-approved RGB-to-grayscale conversion is as follows:

grayscale component = 0.2125*R + 0.7154*G + 0.0721*B

(cf. CCIR Recommendation 709 for modern monitors)
m4551 at abasoft dot it
23-Apr-2004 09:23
here's a function to greyscale an image even from a truecolor source (jpeg or png).

slightly poor quality, but very fast...

function imagegreyscale(&$img, $dither=1) {   
   if (!($t = imagecolorstotal($img))) {
       $t = 256;
       imagetruecolortopalette($img, $dither, $t);   
   }
   for ($c = 0; $c < $t; $c++) {   
       $col = imagecolorsforindex($img, $c);
       $min = min($col['red'],$col['green'],$col['blue']);
       $max = max($col['red'],$col['green'],$col['blue']);
       $i = ($max+$min)/2;
       imagecolorset($img, $c, $i, $i, $i);
   }
}

<imagecolorsetimagecolorstotal>
 Last updated: Tue, 15 Nov 2005