Count Number of Unique Colors in an Image






4.92/5 (4 votes)
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 thecatch
block. Atry
/finally
could have been used on its own. - The
try
/finally
isn't necessary because ausing
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[^].