Quelque chose comme:
Color color = Color.Red;
string colorString = string.Format("#{0:X2}{1:X2}{2:X2}",
color.R, color.G, color.B);
il Faire l'autre est un peu plus complexe que # F00 est une couleur HTML valide (ce qui signifie plein rouge), mais il est encore faisable en utilisant regex, voici une classe petit échantillon:
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);
}
}
Utilisation:
// Display #FF0000
Console.WriteLine(Color.Red.ToHtmlHexadecimal());
// Display #00FF00
Console.WriteLine(HtmlColors.FromHtmlHexadecimal("#0F0").ToHtmlHexadecimal());
// Display #FAF0FE
Console.WriteLine(HtmlColors.FromHtmlHexadecimal("#FAF0FE").ToHtmlHexadecimal());
Cela semble exagéré compte tenu du fait que la méthode que l'OP utilise déjà fait ce qu'ils ont besoin de faire. –
Il n'a pas, j'ai besoin des codes HEX indépendamment de si est une couleur HTML valide. J'ai donc besoin de l'Hex pour White et non de 'White'. – Damien
C'est pourquoi je n'ai pas posté un analyseur complet, car je ne sais pas ce qui est exactement requis par l'OP ... il semble refuser d'utiliser des noms de couleurs pour une raison étrange ...Et aucune API que je connais ne fait "Conversion de couleur comme le HTML le fait mais sans jamais utiliser des noms de couleurs standard" –