Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Count Number of Unique Colors in an Image

0.00/5 (No votes)
20 Feb 2011 1  
Just a few minor improvements to readability and such...The catch/throw isn't needed here, since you are just throwing it without doing anything in the catch block. A try/finally could have been used on its own.The try/finally isn't necessary because a using statement can achieve the same...
Just a few minor improvements to readability and such...

  • The catch/throw isn't needed here, since you are just throwing it without doing anything in the catch block. A try/finally could have been used on its own.
  • The try/finally isn't necessary because a using statement can achieve the same result without the extra code.

public static int CountImageColors(string fileName)
{
    HashSet<Color> colors = new HashSet<Color>();
 
    if (File.Exists(fileName))
    {
        using (Bitmap bmp = new Bitmap(fileName))
        {
            for (int x = 0; x < bmp.Width; ++x)
            {
                for (int y = 0; y < bmp.Height; ++y)
                {
                    colors.Add(bmp.GetPixel(x, y));
                }
            }
        }
    }

    return colors.Count;
}


In addition to the above, you could also use unsafe code to read out the pixels even faster, an example can be found here[^].

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here