First, use the imagecreatefromgif() function to load the GIF image. This function returns an image resource.
$filename = 'example.gif';
$image = imagecreatefromgif($filename);
if (!$image) {
die('Failed to load GIF image');
}
Next, call the imagecolorstotal function and pass in the image resource to get the total number of colors used.
$colorCount = imagecolorstotal($image);
You can directly print the color count to verify the result.
echo "Total number of colors used in the image: " . $colorCount;
After you're done with the image, it’s good practice to destroy the image resource to free up memory.
imagedestroy($image);
<?php
$filename = 'example.gif';
$image = imagecreatefromgif($filename);
if (!$image) {
die('Failed to load GIF image');
}
<p>$colorCount = imagecolorstotal($image);<br>
echo "Total number of colors used in the image: " . $colorCount;</p>
<p>imagedestroy($image);<br>
?><br>
Make sure the GD library is enabled in your PHP environment; otherwise, the related functions won’t work.
imagecolorstotal only works with palette-based images. It typically returns 0 for true color images.
GIF images can use up to 256 colors, so the maximum value returned will not exceed 256.