如何将RGB颜色更改为HSV?在C#语言中.我没有任何外部库搜索非常快的方法.
注意Color.GetSaturation()
并Color.GetBrightness()
返回HSL值,而不是HSV.
以下代码演示了不同之处.
Color original = Color.FromArgb(50, 120, 200); // original = {Name=ff3278c8, ARGB=(255, 50, 120, 200)} double hue; double saturation; double value; ColorToHSV(original, out hue, out saturation, out value); // hue = 212.0 // saturation = 0.75 // value = 0.78431372549019607 Color copy = ColorFromHSV(hue, saturation, value); // copy = {Name=ff3278c8, ARGB=(255, 50, 120, 200)} // Compare that to the HSL values that the .NET framework provides: original.GetHue(); // 212.0 original.GetSaturation(); // 0.6 original.GetBrightness(); // 0.490196079
以下C#代码就是您想要的.它使用维基百科上描述的算法在RGB和HSV之间进行转换.范围为0 - 360表示hue
,0 - 1表示saturation
或value
.
public static void ColorToHSV(Color color, out double hue, out double saturation, out double value) { int max = Math.Max(color.R, Math.Max(color.G, color.B)); int min = Math.Min(color.R, Math.Min(color.G, color.B)); hue = color.GetHue(); saturation = (max == 0) ? 0 : 1d - (1d * min / max); value = max / 255d; } public static Color ColorFromHSV(double hue, double saturation, double value) { int hi = Convert.ToInt32(Math.Floor(hue / 60)) % 6; double f = hue / 60 - Math.Floor(hue / 60); value = value * 255; int v = Convert.ToInt32(value); int p = Convert.ToInt32(value * (1 - saturation)); int q = Convert.ToInt32(value * (1 - f * saturation)); int t = Convert.ToInt32(value * (1 - (1 - f) * saturation)); if (hi == 0) return Color.FromArgb(255, v, t, p); else if (hi == 1) return Color.FromArgb(255, q, v, p); else if (hi == 2) return Color.FromArgb(255, p, v, t); else if (hi == 3) return Color.FromArgb(255, p, q, v); else if (hi == 4) return Color.FromArgb(255, t, p, v); else return Color.FromArgb(255, v, p, q); }
您是否考虑过简单地使用System.Drawing命名空间?例如:
System.Drawing.Color color = System.Drawing.Color.FromArgb(red, green, blue); float hue = color.GetHue(); float saturation = color.GetSaturation(); float lightness = color.GetBrightness();
请注意,这并不是您所要求的(请参阅HSL和HSV之间的差异,而Color类没有从HSL/HSV转换回来,但后者相当容易添加.
这里有一个C实现:
http://www.cs.rit.edu/~ncs/color/t_convert.html
转换为C#应该非常简单,因为几乎没有函数被调用 - 只是计算.
通过Google找到