How to Get the Color from a Hexadecimal Color Code Using .Net

How do I get the color from a hexadecimal color code using .NET?

I'm assuming that's an ARGB code... Are you referring to System.Drawing.Color or System.Windows.Media.Color? The latter is used in WPF for example. I haven't seen anyone mention it yet, so just in case you were looking for it:

using System.Windows.Media;

Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");

How to convert Hexadecimal #FFFFFF to System.Drawing.Color


string hex = "#FFFFFF";
Color _color = System.Drawing.ColorTranslator.FromHtml(hex);

Note: the hash is important!

Get Color from hex in ASP.NET Core

I didn't found library that would handle alpha, so I write my own.

using System;
using System.Drawing;
using System.Globalization;

namespace Color.Library
{
public class ColorManager
{
public static Color FromHex(string hex)
{
FromHex(hex, out var a, out var r, out var g, out var b);

return Color.FromArgb(a, r, g, b);
}

public static void FromHex(string hex, out byte a, out byte r, out byte g, out byte b)
{
hex = ToRgbaHex(hex);
if (hex == null || !uint.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var packedValue))
{
throw new ArgumentException("Hexadecimal string is not in the correct format.", nameof(hex));
}

a = (byte) (packedValue >> 0);
r = (byte) (packedValue >> 24);
g = (byte) (packedValue >> 16);
b = (byte) (packedValue >> 8);
}


private static string ToRgbaHex(string hex)
{
hex = hex.StartsWith("#") ? hex.Substring(1) : hex;

if (hex.Length == 8)
{
return hex;
}

if (hex.Length == 6)
{
return hex + "FF";
}

if (hex.Length < 3 || hex.Length > 4)
{
return null;
}

//Handle values like #3B2
string red = char.ToString(hex[0]);
string green = char.ToString(hex[1]);
string blue = char.ToString(hex[2]);
string alpha = hex.Length == 3 ? "F" : char.ToString(hex[3]);


return string.Concat(red, red, green, green, blue, blue, alpha, alpha);
}
}
}

Use case:

ColorManager.FromHex("#C3B271");
ColorManager.FromHex("#CCC");
ColorManager.FromHex("#C3B27144");
ColorManager.FromHex("#C3B27144", out var a, out var r, out var g, out var b);

I borrow most of the code from ImageSharp library.

How to get the hex color code from a color dialog in visual studio?

You can try this

  1. Get ARGB (Alpha, Red, Green, Blue) representation for the color
  2. Filter out Alpha channel: & 0x00FFFFFF
  3. Format out the value as hexadecimal ("X6")

Implementation

  String code = (colorDialog1.Color.ToArgb() & 0x00FFFFFF).ToString("X6");

Edit: if you want to get Color back from code, try FromArgb:

  string code = "FFDDAA";

Color color = Color.FromArgb(Convert.ToInt32(code, 16));

get color from hexadecimal

You can use ColorTranslator.FromHtml():

var c =  System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
var thisPen = new System.Drawing.SolidBrush(c);

How to get System.Windows.Media.Color From From HEX Windows 8 Application

finally I found one method that return color from hex string

 public System.Windows.Media.Color ConvertStringToColor(String hex)
{
//remove the # at the front
hex = hex.Replace("#", "");

byte a = 255;
byte r = 255;
byte g = 255;
byte b = 255;

int start = 0;

//handle ARGB strings (8 characters long)
if (hex.Length == 8)
{
a = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
start = 2;
}

//convert RGB characters to bytes
r = byte.Parse(hex.Substring(start, 2), System.Globalization.NumberStyles.HexNumber);
g = byte.Parse(hex.Substring(start + 2, 2), System.Globalization.NumberStyles.HexNumber);
b = byte.Parse(hex.Substring(start + 4, 2), System.Globalization.NumberStyles.HexNumber);

return System.Windows.Media.Color.FromArgb(a, r, g, b);
}

Convert .Net Color Objects to HEX codes and Back

Something like :

Color color = Color.Red;
string colorString = string.Format("#{0:X2}{1:X2}{2:X2}",
color.R, color.G, color.B);

Doing it the other way is a little more complex as #F00 is a valid html color (meaning full red) but it is still doable using regex, here is a small sample class :

using System;
using System.Diagnostics;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Collections.Generic;

public static class HtmlColors
{
public static string ToHtmlHexadecimal(this Color color)
{
return string.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
}

static Regex htmlColorRegex = new Regex(
@"^#((?'R'[0-9a-f]{2})(?'G'[0-9a-f]{2})(?'B'[0-9a-f]{2}))"
+ @"|((?'R'[0-9a-f])(?'G'[0-9a-f])(?'B'[0-9a-f]))$",
RegexOptions.Compiled | RegexOptions.IgnoreCase);

public static Color FromHtmlHexadecimal(string colorString)
{
if (colorString == null)
{
throw new ArgumentNullException("colorString");
}

var match = htmlColorRegex.Match(colorString);
if (!match.Success)
{
var msg = "The string \"{0}\" doesn't represent"
msg += "a valid HTML hexadecimal color";
msg = string.Format(msg, colorString);

throw new ArgumentException(msg,
"colorString");
}

return Color.FromArgb(
ColorComponentToValue(match.Groups["R"].Value),
ColorComponentToValue(match.Groups["G"].Value),
ColorComponentToValue(match.Groups["B"].Value));
}

static int ColorComponentToValue(string component)
{
Debug.Assert(component != null);
Debug.Assert(component.Length > 0);
Debug.Assert(component.Length <= 2);

if (component.Length == 1)
{
component += component;
}

return int.Parse(component,
System.Globalization.NumberStyles.HexNumber);
}
}

Usage :

// Display #FF0000
Console.WriteLine(Color.Red.ToHtmlHexadecimal());

// Display #00FF00
Console.WriteLine(HtmlColors.FromHtmlHexadecimal("#0F0").ToHtmlHexadecimal());

// Display #FAF0FE
Console.WriteLine(HtmlColors.FromHtmlHexadecimal("#FAF0FE").ToHtmlHexadecimal());

convert hex code to color name

I stumbled upon a german site that does exactly what you want:

/// <summary>
/// Gets the System.Drawing.Color object from hex string.
/// </summary>
/// <param name="hexString">The hex string.</param>
/// <returns></returns>
private System.Drawing.Color GetSystemDrawingColorFromHexString(string hexString)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(hexString, @"[#]([0-9]|[a-f]|[A-F]){6}\b"))
throw new ArgumentException();
int red = int.Parse(hexString.Substring(1, 2), NumberStyles.HexNumber);
int green = int.Parse(hexString.Substring(3, 2), NumberStyles.HexNumber);
int blue = int.Parse(hexString.Substring(5, 2), NumberStyles.HexNumber);
return Color.FromArgb(red, green, blue);
}

To get the color name you can use it as follows to get the KnownColor:

private KnownColor GetColor(string colorCode)
{
Color color = GetSystemDrawingColorFromHexString(colorCode);
return color.GetKnownColor();
}

However, System.Color.GetKnownColor seems to be removed in newer versions of .NET



Related Topics



Leave a reply



Submit