imagecolorresolvealpha() function in PHP

The imagecolorresolvealpha() function in PHP gets the index of a specified color with alpha transparency in an image's palette. If the color doesn't exist, it allocates a new color index or returns the closest match.

Syntax

imagecolorresolvealpha(resource $image, int $red, int $green, int $blue, int $alpha)

Parameters

  • image − An image resource created by functions like imagecreatetruecolor() or imagecreatefromgif()

  • red − Red component value (0-255)

  • green − Green component value (0-255)

  • blue − Blue component value (0-255)

  • alpha − Alpha transparency value (0-127), where 0 is completely opaque and 127 is completely transparent

Return Value

Returns the color index as an integer. If the exact color exists in the palette, its index is returned. Otherwise, a new color is allocated or the closest match is returned.

Example

The following example demonstrates resolving color indices with alpha transparency ?

<?php
    // Create an image from GIF file
    $img = imagecreatefromgif('/images/sample.gif');
    
    // Array to store color indices
    $colors = array();
    
    // Resolve different RGBA colors
    $colors[] = imagecolorresolvealpha($img, 120, 0, 190, 0);    // Purple, opaque
    $colors[] = imagecolorresolvealpha($img, 110, 0, 140, 0);    // Dark purple, opaque  
    $colors[] = imagecolorresolvealpha($img, 120, 190, 0, 0);    // Yellow-green, opaque
    $colors[] = imagecolorresolvealpha($img, 255, 0, 0, 64);     // Red, semi-transparent
    
    // Display the resolved color indices
    print_r($colors);
    
    // Clean up memory
    imagedestroy($img);
?>
Array
(
    [0] => 128
    [1] => 129  
    [2] => 130
    [3] => 131
)

How It Works

The function first searches the image's color palette for an exact RGBA match. If found, it returns that color's index. If not found, it attempts to allocate a new color slot. For palette images with limited colors, it may return the index of the closest matching color.

Conclusion

The imagecolorresolvealpha() function provides a reliable way to work with transparent colors in GD images. It ensures you get a valid color index whether the exact color exists or needs to be created in the palette.

Updated on: 2026-03-15T08:05:49+05:30

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements