Computer >> Computer tutorials >  >> Programming >> PHP

imagecolorclosest() function in PHP


The imagecolorclosest() function gets the index of the closest color to the specified color.

Syntax

imagecolorallocatealpha (img, red, green, blue)

Parameters

  • img: Image resource created with imagecreatetruecolor().

  • red: Red color component

  • green: Green color component

  • blue: Blue color component

Return

The imagecolorclosest() function returns the index of the closest color, in the palette of the image.

Example

The following is an example:

<?php
   $img = imagecreatefrompng('https://www.tutorialspoint.com/assets/videos/courses/19/images/course_19_image.png');
   imagetruecolortopalette($img, false, 255);
   $val = imagecolorclosest($img, 20, 90, 140);
   $val = imagecolorsforindex($img, $val);
   $val = "({$val['red']}, {$val['green']}, {$val['blue']})";
   echo "Closest = " . $val;
   imagedestroy($img);
?>

Output

The following is the output:

Closest = (44, 118, 140)

Example

Let us see another example wherein we have different image and color components:

<?php
$img = imagecreatefrompng('https://www.tutorialspoint.com/images/Swift.png');
imagetruecolortopalette($img, false, 255);
$val = imagecolorclosest($img, 10, 130, 80);
$val = imagecolorsforindex($img, $val);
$val = "({$val['red']}, {$val['green']}, {$val['blue']})";
echo "Closest = " . $val;
imagedestroy($img);
?>

Output

The following is the output:

Closest = (228, 74, 76)