Hello everyone, I am a wolf at the end of the desert.

前几天刚上线一个颜色值转换工具,当然这是借鉴的,可实现:
- Conversion between HEX, RGB, RGBA, ARGB, and HSL;
- It shows a very useful CSS color table that can be found and used during development: 147 color names (17 standard colors plus 130 other colors) defined in HTML and CSS color specifications.

This article briefly lists a few translations and comparisons between relevant JS code and C#code when developing this tool, so as to facilitate subsequent similar development reference.
JS文件:点这
- Color Value HEX Conversion
提取HEX#9A3B34中R(Red)、G(Green)、B(Blue)的色值。
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. Color Value RGBA 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;
}
It is very convenient to translate JS code into C#code through chatGPT. It is very fast to make a Blazor tool. Other online programming language translation websites are not ideal. In more cases, you still need to modify them manually.
- 本工具地址:Blazor Server版, Blazor Wasm版
- 网站源码及Issue:源码,Issue
- .NET版本: .NET 8.0.0-preview.5.23280.8
- WeChat technology group: To add webmaster WeChat (codewf), you must note the two words "join the group"
- QQ technology group: 771992300