Friday, November 21, 2025
HomeLanguagesPHP | imagecolorclosest() Function

PHP | imagecolorclosest() Function

The imagecolorclosest() function is an inbuilt function in PHP which is used to get the index of the closest color in the given image. This function returns the index of the color in the palette of the image which is closest to the specified RGB value.

Syntax:

int imagecolorclosest( $image, $red, $green, $blue )

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

  • $image: It is returned by one of the image creation functions, such as imagecreatetruecolor(). It is used to create size of image.
  • $red: This parameter is used to set value of red color component.
  • $green: This parameter is used to set value of green color component.
  • $blue: This parameter is used to set value of blue color component.

Return Value: This function returns the index of the closest color, in the palette of the image.

Below programs illustrate the imagecolorclosest() function in PHP.

Program 1:




<?php
  
// Start with an image and convert it to a palette-based image
$image = imagecreatefrompng(
  
imagetruecolortopalette($image, false, 255);
  
//  Search closest color
$result = imagecolorclosest($image, 7, 150, 10);
  
$result = imagecolorsforindex($image, $result);
  
$result = "({$result['red']}, {$result['green']}, {$result['blue']})";
  
echo "Closest color: " . $result;
  
imagedestroy($image);
  
?>


Output:

Closest color: (4, 146, 12)

Program 2:




<?php
  
// Start with an image and convert it to a palette-based image
$image = imagecreatefrompng(
  
imagetruecolortopalette($image, false, 255);
  
// Search RGB colors
$color = array(
    array(7, 150, 0),
    array(53, 190, 255),
    array(255, 165, 54)
);
  
// Loop to find the closest color to the given RGB color
foreach($color as $id => $rgb)
{
    $result = imagecolorclosest($image, $rgb[0], $rgb[1], $rgb[2]);
    $result = imagecolorsforindex($image, $result);
    $result = "({$result['red']}, {$result['green']}, {$result['blue']})";
  
    echo "Given color: ($rgb[0], $rgb[1], $rgb[2]) => Closest match: $result<br>";
}
  
imagedestroy($image);
  
?>


Output:

Given color: (7, 150, 0) => Closest match: (4, 142, 4)
Given color: (53, 190, 255) => Closest match: (148, 174, 180)
Given color: (255, 165, 54) => Closest match: (148, 162, 164)

Return Value:

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

RELATED ARTICLES

Most Popular

Dominic
32405 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6781 POSTS0 COMMENTS
Nicole Veronica
11928 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11997 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7166 POSTS0 COMMENTS
Thapelo Manthata
6862 POSTS0 COMMENTS
Umr Jansen
6847 POSTS0 COMMENTS