English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP imagecolorclosestalpha() Get the index of the color closest to the specified color and opacity

PHP Image Processing

imagecolorclosestalpha — Get the index of the color closest to the specified color and opacity.

Syntax

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

Returns the color in the image palette that is 'closest' to the specified RGB value and alpha depth.

parameter

  • imageThe image resource returned by the image creation function (such as imagecreatetruecolor()).

  • redred

  • The value of the red component.green

  • The value of the green component.blue

  • The value of the blue component.alpha 127 The value between 0 and127 represents complete transparency.

The color parameter is a value between 0 and 255 is an integer between 0 and 255, or a hexadecimal number between 0x00 and 0xFF.

Return value

Return the index of the closest color in the palette.

Example

Search for a set of colors in an image.

<?php
// Start from an image and convert it to a palette-based image
$im = imagecreatefrompng('figures/imagecolorclosest.png');
imagetruecolortopalette($im, false, 255);
// Search color (RGB)
$colors = array(
    array(254, 145, 154, 50),
    array(153, 145, 188, 127),
    array(153, 90, 145, 0),
    array(255, 137, 92, 84)
);
// Loop through to find the closest color in the palette
// Return the number of searches, the searched RGB and the closest matching RGB
foreach($colors as $id => $rgb)
{
    $result = imagecolorclosestalpha($im, $rgb[0], $rgb[1], $rgb[2], $rgb[3]);
    $result = imagecolorsforindex($im, $result);
    $result = "({$result['red']}, {$result['green']}, {$result['blue']}, {$result['alpha']})";
    echo "#$id: Search ($rgb[0], $rgb[1], $rgb[2], $rgb[3); Closest match: $result.\n";
}
imagedestroy($im);
?>

The output of the above examples is similar to:

#0: Search (254, 145, 154, 50); Closest match: (252, 150, 148, 0).
#1: Search (153, 145, 188, 127); Closest match: (148, 150, 196, 0).
#2: Search (153, 90, 145, 0); Closest match: (148, 90, 156, 0).
#3: Search (255, 137, 92, 84); Closest match: (252, 150, 92, 0).

Related articles

PHP Image Processing