Hello everyone, I am Wolf at the End of the Desert.

A few days ago, I just launched a color value conversion tool, which is of course a reference from others. It can:
- Convert between HEX, RGB, RGBA, ARGB, and HSL;
- Display a very practical CSS color table for use during development: 147 color names defined in the HTML and CSS color specification (17 standard colors plus 130 additional colors).

This article briefly lists a few places where the JS code and C# code were compared during the development of this tool, for your reference in similar future development.
JS file: Click here
1. HEX Color Value Conversion
Extract the R (Red), G (Green), B (Blue) values from the HEX #9A3B34.
JS code
function parseHEX(val) {
let color = new Color();
try {
let rgx = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
let hex = val.replace(rgx, function (m, r, g, b) {
return r + r + g + g + b + b;
});
let rgb = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
color.r = parseInt(rgb[1], 16);
color.g = parseInt(rgb[2], 16);
color.b = parseInt(rgb[3], 16);
} catch (e) {
console.log(e)
}
return color;
}
C# code
public static Color? ParseHEX(string hexColor)
{
hexColor = hexColor.TrimStart('#');
Regex regex = new(@"^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$");
var match = regex.Match(hexColor);
if (match?.Success == true)
{
int red = Convert.ToInt32(match.Groups[1].Value, 16);
int green = Convert.ToInt32(match.Groups[2].Value, 16);
int blue = Convert.ToInt32(match.Groups[3].Value, 16);
return new Color(red, green, blue);
}
else
{
return null;
}
}
2. RGBA Color Value Conversion
The conversion logic is basically the same as above.
JS code
function parseRGBA(val) {
let color = new Color();
try {
let rgba = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/.exec(val);
color.r = parseInt(rgba[1]);
color.g = parseInt(rgba[2]);
color.b = parseInt(rgba[3]);
color.a = parseFloat(rgba[4] || 1);
} catch (e) {
console.log(e)
}
return color;
}
C# code
public static Color? ParseRGBA(string color)
{
Regex regex = new Regex(@"^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$");
var match = regex.Match(color);
if (match?.Success == true)
{
int r = int.Parse(match.Groups[1].Value);
int g = int.Parse(match.Groups[2].Value);
int b = int.Parse(match.Groups[3].Value);
if (!double.TryParse(match.Groups[4].Value, out double a))
{
a = 1;
}
return new Color(r, g, b, a);
}
return null;
}
Using ChatGPT, it is very convenient to translate JS code into C# code, making it quick to build a Blazor tool. Other online programming language translation websites are not ideal, and most of the time manual adjustments are still needed.
- Tool address: Blazor Server version, Blazor Wasm version
- Website source code and Issues: Source code, Issue
- .NET version: .NET 8.0.0-preview.5.23280.8
- WeChat technical group: Add the site owner's WeChat (codewf), be sure to note the two characters "入群" (join group)
- QQ technical group: 771992300