imagecolorat() function in PHP

The imagecolorat() function gets the color index of a pixel at specific coordinates in an image resource. It's useful for analyzing pixel colors in image processing tasks.

Syntax

imagecolorat($image, $x, $y)

Parameters

  • $image − An image resource created by functions like imagecreate() or imagecreatefromjpeg()

  • $x − The x-coordinate of the pixel (horizontal position)

  • $y − The y-coordinate of the pixel (vertical position)

Return Value

Returns the color index as an integer, or FALSE on failure. For truecolor images, this returns the RGB value as a packed integer.

Example 1: Getting Pixel Color from Created Image

Here's how to get the color of a pixel from a simple created image ?

<?php
    // Create a 100x100 image
    $img = imagecreate(100, 100);
    
    // Define colors
    $white = imagecolorallocate($img, 255, 255, 255);
    $red = imagecolorallocate($img, 255, 0, 0);
    
    // Fill background with white
    imagefill($img, 0, 0, $white);
    
    // Draw a red rectangle
    imagefilledrectangle($img, 20, 20, 80, 80, $red);
    
    // Get color at white background (coordinates 10, 10)
    $color_white = imagecolorat($img, 10, 10);
    echo "Color index at (10,10): " . $color_white . "
"; // Get color at red rectangle (coordinates 50, 50) $color_red = imagecolorat($img, 50, 50); echo "Color index at (50,50): " . $color_red . "
"; imagedestroy($img); ?>
Color index at (10,10): 0
Color index at (50,50): 1

Example 2: Converting Color Index to RGB Values

To get actual RGB values, combine imagecolorat() with imagecolorsforindex() ?

<?php
    // Create truecolor image
    $img = imagecreatetruecolor(100, 100);
    
    // Create colors
    $blue = imagecolorallocate($img, 0, 100, 200);
    $yellow = imagecolorallocate($img, 255, 255, 0);
    
    // Fill with blue background
    imagefill($img, 0, 0, $blue);
    
    // Add yellow circle
    imagefilledellipse($img, 50, 50, 30, 30, $yellow);
    
    // Get color at blue area
    $color_index = imagecolorat($img, 25, 25);
    $rgb_values = imagecolorsforindex($img, $color_index);
    
    echo "RGB at (25,25): ";
    print_r($rgb_values);
    
    imagedestroy($img);
?>
RGB at (25,25): Array
(
    [red] => 0
    [green] => 100
    [blue] => 200
    [alpha] => 0
)

Key Points

  • Coordinates start from (0,0) at the top-left corner

  • For palette-based images, returns the color index in the palette

  • For truecolor images, returns the RGB value as a packed integer

  • Use imagecolorsforindex() to convert color index to RGB array

Conclusion

The imagecolorat() function is essential for pixel-level image analysis in PHP. Use it with imagecolorsforindex() to extract meaningful RGB color information from any point in an image.

Updated on: 2026-03-15T07:48:14+05:30

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements