Convert HTML Color Code to System.Drawing.Color and ColorMatrix

.NET Framework provides implementation of the System.Drawing.Color and several satellite classes like System.Drawing.KnownColor and System.Drawing.SystemColors and they are based on ARGB schema.

To convert HTML color code to these colors, you will use the methods FromHtml() and ToHtml() of System.Drawing.ColorTranslator

A calculation will be necessary to convert it to System.Drawing.Imaging.ColorMatrix.

 

HTML Color Code System.Drawing.Color System.Drawing.Imaging.ColorMatrix
 
#00FFEC
ARGB=
(255, 0, 255, 236)

0 1.0 0.92549026 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 1 0
0 0 0 0 1


 


public static System.Drawing.Color ToColor(string newColorInHtml)
{
    var newColor = System.Drawing.Color.Transparent;
    if (!string.IsNullOrWhiteSpace(newColorInHtml))
    {
        if (newColorInHtml[0] != '#')
            newColorInHtml = "#" + newColorInHtml;

        newColor = System.Drawing.ColorTranslator.FromHtml(newColorInHtml);
    }

    return newColor;
}

public static System.Drawing.Imaging.ColorMatrix ToColorMatrix(System.Drawing.Color color)
{
    //convert the RGB values to scale of 0-1
    float r = (1.0f / 255) * color.R;
    float b = (1.0f / 255) * color.B;
    float g = (1.0f / 255) * color.G;

    var colorMatrix = new System.Drawing.Imaging.ColorMatrix(
        new float[][]
        {
            new float[] {r, g, b, 0, 0},
            new float[] {0,  0,  0,  0, 0},
            new float[] {0,  0, 0,  0, 0},
            new float[] {0,  0,  0,  1, 0},
            new float[] {0, 0, 0, 0, 1}
        });

    return colorMatrix;
}

 

 

Advertisements

One thought on “Convert HTML Color Code to System.Drawing.Color and ColorMatrix

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s