• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 320
  • Last Modified:

C# Code Snippet to return array of colors used in a bitmap

Any idea how i can determine a discreet list of colors that are used in a bitmap.  For example, if a bitmap contained a primitive American Flag, the method would return Color.Red, Color.White, Color.Blue.   I intend to have the return values sorted by usage within the bitmap.  So the return would be red, white then blue.

I want to write a method in C# which has the following signature?

using System;
using System.Drawing;

public static Color[] GetColorsFromBitmap(Bitmap bitmap)
{
     // What goes here?  How do i loop through the pixels (assuming i have to)?
}


0
RXGeorge
Asked:
RXGeorge
1 Solution
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Create a class to hold each color along with its count:

    public class ColorData
    {
        public Color color;
        public int count;
    }

Then the code might look something like:  
public static Color[] GetColorsFromBitmap(Bitmap bitmap)
        {
            Dictionary<Color, ColorData> data = new Dictionary<Color, ColorData>();
            for (int x = 0; x < bitmap.Width; x++)
            {
                for (int y = 0; y < bitmap.Height; y++)
                {
                    if (data.ContainsKey(bitmap.GetPixel(x,y)))
                    {
                        data[bitmap.GetPixel(x, y)].count++;
                    }
                    else
                    {
                        ColorData cd = new ColorData();
                        cd.color = bitmap.GetPixel(x, y);
                        cd.count = 1;
                        data.Add(cd.color, cd);
                    }
                }
            }

            List<ColorData> sortedData = data.Values.ToList();
            sortedData.Sort( delegate(ColorData cd1, ColorData cd2) { return cd2.count.CompareTo(cd1.count); } );
            List<Color> colors = new List<Color>();
            foreach (ColorData cd in sortedData)
            {
                colors.Add(cd.color);
            }
            return colors.ToArray();
        }

Open in new window

0
 
RXGeorgeAuthor Commented:
Fantastic,  thanks so much.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now