[ACCEPTED]-Convert .Net Color Objects to HEX codes and Back-system.drawing.color
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 4 a little more complex as #F00 is a valid 3 html color (meaning full red) but it is 2 still doable using regex, here is a small 1 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());
"White" is a valid HTML color. Please 9 see ColorTranslator.ToHtml
:
This method translates a Color structure 8 to a string representation of an HTML 7 color. This is the commonly used name 6 of a color, such as "Red", "Blue", or 5 "Green", and not string representation 4 of a numeric color value, such as "FF33AA".
If 3 your color cannot be mapped to a HTML color 2 string this method will return the valid 1 hex for the color. See this example:
using System;
using System.Drawing;
class Program
{
static void Main()
{
Console.WriteLine(ColorTranslator.ToHtml(Color.White));
Console.WriteLine(ColorTranslator.ToHtml(Color.FromArgb(32,67,89)));
}
}
If you will convert the color back with 11 {ColorTranslator.FromHTML}, 'White' is a 10 valid string for a HTML color. But I've 9 found that this implementation needs a # symbol 8 before the string that represents the color 7 if it isn't common (for example, it works 6 with White, and #FFFFFF, but it doesn't 5 with #White or FFFFFF). So I tried putting 4 the conversion inside a try/catch block, made 3 the conversion adding '#'to the string and 2 if it threw an exception then I caught it 1 and made the conversion without #.
I have written my own .net extension for 2 simple converting from hex to integer and 1 integer(ARGB) to color and vise versa:
Imports System.Drawing
Imports System.Runtime.CompilerServices
Public Module ColorsExt
Private Sub example_for_usage()
Dim hex As String
Dim c As Color = Color.Red
hex = c.ToHexString() 'Converts color to hexadecimal string'
c = hex.ToIntegerFromHex().ToColor() 'Gets Integer value from the hex string and simply convert it to Color()'
End Sub
<Extension> _
Public Function ToColor(ByVal argb As Integer) As Color
Return Color.FromArgb(argb)
End Function
<Extension> _
Public Function ToIntegerFromHex(ByVal argb_hex_string As String) As Integer
Return Int("&H" + argb_hex_string)
End Function
<Extension> _
Public Function ToHexString(ByVal c As Color) As String
Return String.Format("{0:X2}{1:X2}{2:X2}{3:X2}", c.A, c.R, c.G, c.B)
End Function
<Extension> _
Public Sub FromHexString(ByVal c As Color, ByVal hex As String)
c = hex.ToIntegerFromHex().ToColor()
End Sub
<Extension> _
Public Function ToHexString(ByVal c As Integer) As String
Return String.Format("{0:X8}", c)
End Function
<Extension> _
Public Function ToArgb(ByVal c As Color) As Integer
Return (c.A * &HFF0000) + (c.R * &HFF00) + (c.G * &HFF) + (c.B)
End Function
End Module
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.