Skip to content

Instantly share code, notes, and snippets.

@xv
Created May 13, 2020 10:43
Show Gist options
  • Save xv/d7db4fbb08907388cd46f1e9eb1b3d84 to your computer and use it in GitHub Desktop.
Save xv/d7db4fbb08907388cd46f1e9eb1b3d84 to your computer and use it in GitHub Desktop.
A much faster alternative to Microsoft's ColorTranslator.FromHtml() function.
The following benchmark was done by loop-calling the functions 1,000,000 times.
SIX DIGIT TEST:
this.FromHtml: Elapsed=89ms
ColorTranslator.FromHtml: Elapsed=244ms
this.FromHtml: Elapsed=86ms
ColorTranslator.FromHtml: Elapsed=232ms
this.FromHtml: Elapsed=87ms
ColorTranslator.FromHtml: Elapsed=235ms
this.FromHtml: Elapsed=86ms
ColorTranslator.FromHtml: Elapsed=234ms
this.FromHtml: Elapsed=86ms
ColorTranslator.FromHtml: Elapsed=235ms
THREE DIGIT TEST:
this.FromHtml: Elapsed=68ms
ColorTranslator.FromHtml: Elapsed=276ms
this.FromHtml: Elapsed=68ms
ColorTranslator.FromHtml: Elapsed=258ms
this.FromHtml: Elapsed=67ms
ColorTranslator.FromHtml: Elapsed=256ms
this.FromHtml: Elapsed=67ms
ColorTranslator.FromHtml: Elapsed=258ms
this.FromHtml: Elapsed=67ms
ColorTranslator.FromHtml: Elapsed=261ms
/// <summary>
/// Translates an HTML-format color value to a GDI+
/// <see cref="System.Drawing.Color"/> structure.
/// </summary>
///
/// <param name="htmlVal">
/// A 3 or 6 digit hexadecimal value to translate. Do not include the
/// leading "#" sign.
/// </param>
///
/// <returns>
/// Returns the translated structure.
/// </returns>
private Color FromHtml(string htmlVal)
{
var value = Convert.ToInt32(htmlVal, 16);
var color = Color.Empty;
switch (htmlVal.Length)
{
case 6:
const int mask = 0xFF;
color = Color.FromArgb
(
(value >> 16) & mask,
(value >> 8) & mask,
(value) & mask
);
break;
case 3:
var argb = (255 << 24) |
(value & 0xF00) << 8 |
(value & 0x0F0) << 4 |
(value & 0x00F);
argb |= argb << 4;
color = Color.FromArgb(argb);
break;
}
return color;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment