imagecolorclosesthwb() function in PHP

The imagecolorclosesthwb() function finds the index of the color that most closely matches a given RGB color using the HWB (Hue, Whiteness, Blackness) color model. This function is useful for color matching in palette−based images.

Syntax

imagecolorclosesthwb($image, $red, $green, $blue)

Parameters

  • $image − An image resource created by image creation functions like imagecreate() or imagecreatefromgif()

  • $red − Red color component value (0−255)

  • $green − Green color component value (0−255)

  • $blue − Blue color component value (0−255)

Return Value

Returns an integer representing the index of the color in the image palette that has the closest HWB values to the specified RGB color.

Example

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

<?php
    // Create a palette-based image
    $img = imagecreate(100, 100);
    
    // Allocate some colors
    $white = imagecolorallocate($img, 255, 255, 255);
    $red = imagecolorallocate($img, 255, 0, 0);
    $green = imagecolorallocate($img, 0, 255, 0);
    $blue = imagecolorallocate($img, 0, 0, 255);
    
    // Find closest color to RGB(200, 50, 50) - should be close to red
    $closest = imagecolorclosesthwb($img, 200, 50, 50);
    
    echo "Closest color index: " . $closest;
    
    // Get the RGB values of the closest color
    $rgb = imagecolorsforindex($img, $closest);
    echo "\nClosest color RGB: " . $rgb['red'] . ", " . $rgb['green'] . ", " . $rgb['blue'];
    
    imagedestroy($img);
?>

The output of the above code is ?

Closest color index: 1
Closest color RGB: 255, 0, 0

Key Points

  • This function only works with palette−based images, not truecolor images

  • The HWB color model considers hue, whiteness, and blackness for better perceptual color matching

  • RGB values should be in the range 0−255

  • Use imagecolorsforindex() to get the actual RGB values of the returned color index

Conclusion

The imagecolorclosesthwb() function provides an efficient way to find the closest color match in palette−based images using the HWB color model, making it ideal for color quantization and palette reduction tasks.

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

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements