C#: How to Use HTML Colors in Your Code

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

There are many ways to specify HTML color codes in C#. The .net framework has a great object for dealing with colors called Color.

Here are some of the ways that you can create a Color object.

C# Source Code Example to Modify Color

// if you have an HTML string
var lightGray = System.Drawing.ColorTranslator.FromHtml("#D3D3D3");

// if you have 3 hex numbers
var lightGray = System.Drawing.Color.FromArgb(0xD3, 0xD3, 0xD3);

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

// if you want to specify an alpha (transperancy) you can use FromArgb
// the first int is the transperancy. 255 is solid while 0 is fully transperant
var lightGray = Color.FromArgb(255, 0xD3, 0xD3, 0xD3);

// you can also use integers with FromArgb
var lightGray = Color.FromArgb(255, 211, 211, 211);

// if you are using WPF and you want to specify an alpha in HTML style you can do this
using System.Windows.Media;
var lightGray = (Color)ColorConverter.ConvertFromString("#FFD3D3D3");

All of these methods will generate the same Color object and you can use any of them as you see fit.

C# Color Object

The C# Color object is very useful and has some great properties. We have a guide to help you make use of it.

C# Image Processing

We have many more articles about C# Image Processing that you might want to check out - C# Image Processing.

Leave a reply

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

More from Efundies