imagecolormatch() function in PHP

The imagecolormatch() function adjusts the colors of a palette image to more closely match those of a true color image. This function is useful when you need to optimize a palette-based image to better represent the original true color version.

Syntax

bool imagecolormatch(resource $img1, resource $img2)

Parameters

  • img1 − A true color image resource created with imagecreatetruecolor() function.

  • img2 − A palette image resource with the same dimensions as img1. This image's palette will be modified to match img1.

Return Value

The function returns TRUE on success or FALSE on failure.

Example 1

Here's a basic example demonstrating color matching between a true color image and a palette image −

<?php
    $img1 = imagecreatefrompng('/images/Swift.png');
    $img2 = imagecreate(imagesx($img1), imagesy($img1));
    $color = Array();
    $color[] = imagecolorallocate($img2, 110, 40, 180);
    $color[] = imagecolorallocate($img2, 90, 10, 90);
    $color[] = imagecolorallocate($img2, 66, 170, 110);
    $color[] = imagecolorallocate($img2, 130, 90, 70);
    
    echo imagecolormatch($img1, $img2);
    
    imagedestroy($img1);
    imagedestroy($img2);
?>
1

Example 2

Another example showing color matching with different color combinations −

<?php
    $img1 = imagecreatefrompng('/images/tp-logo-diamond.png');
    $img2 = imagecreate(imagesx($img1), imagesy($img1));
    $color = Array();
    $color[] = imagecolorallocate($img2, 10, 1, 20);
    $color[] = imagecolorallocate($img2, 40, 30, 10);
    $color[] = imagecolorallocate($img2, 15, 100, 50);
    $color[] = imagecolorallocate($img2, 70, 20, 30);
    
    echo imagecolormatch($img1, $img2);
    
    imagedestroy($img1);
    imagedestroy($img2);
?>
1

Conclusion

The imagecolormatch() function is valuable for optimizing palette images to better represent true color originals. It requires the GD extension and both images must have identical dimensions for successful color matching.

Updated on: 2026-03-15T08:07:05+05:30

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements