imagecolorsforindex

(PHP 3, PHP 4, PHP 5)

imagecolorsforindex -- 取得某索引的颜色

说明

array imagecolorsforindex ( resource image, int index )

本函数返回一个具有 red,green,blue 和 alpha 的键名的关联数组,包含了指定颜色索引的相应的值。

例子 1. imagecolorsforindex() 例子

<?php

// 打开一幅图像
$im = imagecreatefrompng('nexen.png');

// 取得一点的颜色
$start_x = 40;
$start_y = 50;
$color_index = imagecolorat($im, $start_x, $start_y);

// 使其可读
$color_tran = imagecolorsforindex($im, $color_index);

// 显示该颜色的值
echo '<pre>';
print_r($color_tran);
echo
'</pre>';

?>

本例将输出:

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

参见 imagecolorat()imagecolorexact()


add a note add a note User Contributed Notes
adspeed.com
24-Aug-2005 07: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
26-Jun-2004 04: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
24-Apr-2004 12: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);
   }
}