C# Color Object

Thumbnail image of Jason Bauer
Jason Bauer
December 24, 2015 (Last Updated: ) | Reading Time: 1 minutes

The C# Color Object is a very convenient way of storing colors in your C# projects. Once you have a Color object you can easily get the RGB and HSB values out of it.

Understanding the Color object is important if you are learning to do any C# work that involves colors.

Creating Color Objects

If you have an HTML color code and you want to make a Color object then you may want to read about how to Create C# Color Objects from HTML Color Codes. The easiest way to create a Color object is from a known color.

// you can specify known color names
var lightGray = Color.LightGray;

If you happen to have the color that you need in a string you can specify it that way as well.

// the color can even be in a string
var lightGray = Color.FromName("lightgray");

If you need to test if the color returned is valid you can look at the alpha channel. It will be 0 for a bad color name.

var lightGray = Color.FromName("not-a-color");
if (lightGray.A == 0)
{
    throw new Exception("That's not a valid color name.");
}

If you want to translate a typed in color string to a proper known color value you can do that too.

var lightGray = Color.FromName("lightgray");

if (lightGray.IsKnownColor)
{
    var colorName = lightGray.ToKnownColor().ToString();
    // colorName is a string with the text "LightGray" in it
}

C# Color Object

Once you have a Color object you can get the individual Red, Green, and Blue components as well as the Alpha (transperancy).

// if you want to retrieve the RGB values of a color it's very simple
var red = lightGray.R;
var green = lightGray.G;
var blue = lightGray.B;
var alpha = lightGray.A;

If you need to be in the HSB (Hue, Saturation, Brightness) gamut it's just as easy.

// if you want the HSB values you can easily get those
var hue = lightGray.GetHue();
var saturation = lightGray.GetSaturation();
var brightness = lightGray.GetBrightness();

C# Image Processing

Be sure to check out our other C# Image Processing Guides located here.

Leave a reply

Thank you! Your comment has been successfully submitted. It will be approved as soon as possible.

More from Efundies