PHP | imagecolorsforindex() Function

The imagecolorsforindex() function is an inbuilt function in PHP which is used to get the colors at the given index. This function returns an array containing red, green, blue and alpha key values for specified color value.

Syntax:

array imagecolorsforindex ( $image, $index )

Parameters: This function accepts two parameters as mentioned above and described below:



  • $image: The imagecreatetruecolor() function is used to create an image in a given size. This function creates blank image of given size.
  • $index: This parameter is used to specify the color index.

Return Value: This function returns an associative array containing red, green, blue and alpha keys value at the given index.

Below programs illustrate the imagecolorsforindex() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
   
// store the image in variable.
$image = imagecreatefrompng(
   
// Calculate rgb pixel value at perticular point.
$rgb = imagecolorat($image, 30, 25);
   
// Assign color name and its value.
$colors = imagecolorsforindex($image, $rgb);
   
var_dump($colors);
?>

chevron_right


Output:

array(4) { 
    ["red"]=> int(34) 
    ["green"]=> int(170) 
    ["blue"]=> int(66) 
    ["alpha"]=> int(0) 
} 

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
   
// store the image in variable.
$image = imagecreatefrompng(
   
// index value
$index_x = 230;
$index_y = 120;
  
// Calculate rgb pixel value at perticular point.
$rgba_color = imagecolorat($image, $index_x, $index_y);
  
// Assign color name and its value.
$colors = imagecolorsforindex($image, $rgba_color);
   
var_dump($colors);
?>

chevron_right


Output:

array(4) { 
    ["red"]=> int(97) 
    ["green"]=> int(57) 
    ["blue"]=> int(104) 
    ["alpha"]=> int(0) 
} 

Related Articles:

Reference: http://php.net/manual/en/function.imagecolorsforindex.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.