imagecolorsforindex() function in PHP

The imagecolorsforindex() function in PHP retrieves the RGBA color values for a specific color index in an image. This is useful when you need to analyze or manipulate colors at specific positions in an image.

Syntax

imagecolorsforindex(resource $image, int $index)

Parameters

  • image − An image resource created by image creation functions like imagecreate() or imagecreatefrompng()

  • index − The color index value obtained from functions like imagecolorat()

Return Value

Returns an associative array containing four keys: red, green, blue, and alpha with their corresponding integer values (0-255 for RGB, 0-127 for alpha where 0 is opaque and 127 is transparent).

Example

Here's how to get color information from a specific pixel in an image −

<?php
    // Create a simple image
    $img = imagecreate(100, 100);
    
    // Allocate some colors
    $white = imagecolorallocate($img, 255, 255, 255);
    $red = imagecolorallocate($img, 255, 0, 0);
    $blue = imagecolorallocate($img, 0, 0, 255);
    
    // Fill image with white background
    imagefill($img, 0, 0, $white);
    
    // Draw a red rectangle
    imagefilledrectangle($img, 10, 10, 50, 50, $red);
    
    // Get color index at position (25, 25) - should be red
    $colorIndex = imagecolorat($img, 25, 25);
    
    // Get RGB values for this color index
    $colors = imagecolorsforindex($img, $colorIndex);
    
    echo "Color information at pixel (25, 25):
"; echo "Red: " . $colors['red'] . "
"; echo "Green: " . $colors['green'] . "
"; echo "Blue: " . $colors['blue'] . "
"; echo "Alpha: " . $colors['alpha'] . "
"; // Clean up imagedestroy($img); ?>
Color information at pixel (25, 25):
Red: 255
Green: 0
Blue: 0
Alpha: 0

Key Points

  • Alpha values range from 0 (opaque) to 127 (transparent)

  • RGB values range from 0 to 255

  • The function works with both palette-based and true color images

  • Always use imagecolorat() first to get the color index before calling this function

Conclusion

The imagecolorsforindex() function is essential for color analysis in PHP image processing, allowing you to extract detailed RGBA information from any pixel in an image for further manipulation or analysis.

Updated on: 2026-03-15T08:06:04+05:30

126 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements