diff --git a/RGB.NET.Core/Helper/ConversionHelper.cs b/RGB.NET.Core/Helper/ConversionHelper.cs
index dca7dab..56bbf62 100644
--- a/RGB.NET.Core/Helper/ConversionHelper.cs
+++ b/RGB.NET.Core/Helper/ConversionHelper.cs
@@ -29,6 +29,32 @@
return new string(c);
}
+ // Source: https://web.archive.org/web/20180224104425/https://stackoverflow.com/questions/623104/byte-to-hex-string/3974535
+ ///
+ /// Converts the HEX-representation of a byte array to that array.
+ ///
+ /// The HEX-string to convert.
+ /// The correspondending byte array.
+ public static byte[] HexToBytes(string hexString)
+ {
+ if ((hexString.Length == 0) || ((hexString.Length % 2) != 0))
+ return new byte[0];
+
+ byte[] buffer = new byte[hexString.Length / 2];
+ for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)
+ {
+ // Convert first half of byte
+ char c = hexString[sx];
+ buffer[bx] = (byte)((c > '9' ? (c > 'Z' ? ((c - 'a') + 10) : ((c - 'A') + 10)) : (c - '0')) << 4);
+
+ // Convert second half of byte
+ c = hexString[++sx];
+ buffer[bx] |= (byte)(c > '9' ? (c > 'Z' ? ((c - 'a') + 10) : ((c - 'A') + 10)) : (c - '0'));
+ }
+
+ return buffer;
+ }
+
#endregion
}
}
diff --git a/RGB.NET.Core/Leds/Color.cs b/RGB.NET.Core/Leds/Color.cs
index 76317e3..cc2208d 100644
--- a/RGB.NET.Core/Leds/Color.cs
+++ b/RGB.NET.Core/Leds/Color.cs
@@ -215,6 +215,28 @@ namespace RGB.NET.Core
return new Color(a, r, g, b);
}
+ ///
+ /// Creates a new instance of the struct using a HEX-string.
+ ///
+ /// The HEX-representation of the color.
+ /// The color created from the HEX-string.
+ public static Color FromHexString(string hexString)
+ {
+ if ((hexString == null) || (hexString.Length < 6))
+ throw new ArgumentException("Invalid hex string", nameof(hexString));
+
+ if (hexString[0] == '#')
+ hexString = hexString.Substring(1);
+
+ byte[] data = ConversionHelper.HexToBytes(hexString);
+ if (data.Length == 3)
+ return new Color(data[0], data[1], data[2]);
+ if (data.Length == 4)
+ return new Color(data[0], data[1], data[2], data[3]);
+
+ throw new ArgumentException("Invalid hex string", nameof(hexString));
+ }
+
#endregion
private static (double h, double s, double v) CaclulateHSVFromRGB(byte r, byte g, byte b)