imagecolorclosest() function in PHP

The imagecolorclosest() function gets the index of the closest color to the specified color in an image's palette. This function is particularly useful when working with palette-based images where you need to find the best match for a specific RGB color.

Syntax

imagecolorclosest(image, red, green, blue)

Parameters

  • image − Image resource created with image creation functions

  • red − Red color component (0-255)

  • green − Green color component (0-255)

  • blue − Blue color component (0-255)

Return Value

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

Example 1

The following example demonstrates finding the closest color match in an image palette ?

<?php
    $img = imagecreatefrompng('/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);
?>
Closest = (44, 118, 140)

Example 2

Let us see another example with different image and color components ?

<?php
    $img = imagecreatefrompng('/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);
?>
Closest = (228, 74, 76)

How It Works

The function works by converting the image to a palette-based format using imagetruecolortopalette(), then comparing the requested RGB values against all colors in the palette to find the closest match using color distance calculations.

Conclusion

The imagecolorclosest() function is essential for color matching in palette-based images. It helps find the best available color when the exact color doesn't exist in the image's palette.

Updated on: 2026-03-15T08:04:48+05:30

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements