Current Location: Home> Latest Articles> How to Use the imagecolorstotal Function to Get the Total Number of Colors in a GIF Image? Step-by-Step Guide

How to Use the imagecolorstotal Function to Get the Total Number of Colors in a GIF Image? Step-by-Step Guide

M66 2025-07-26

Step-by-Step Guide

1. Load the GIF Image

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');
}

2. Use imagecolorstotal to Get the Number of Colors

Next, call the imagecolorstotal function and pass in the image resource to get the total number of colors used.

$colorCount = imagecolorstotal($image);

3. Output the Total Number of Colors

You can directly print the color count to verify the result.

echo "Total number of colors used in the image: " . $colorCount;

4. Free Up Resources (Optional)

After you're done with the image, it’s good practice to destroy the image resource to free up memory.

imagedestroy($image);

Complete Example Code

<?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>


Things to Note

  • 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.