c# - 如何将 RGB 颜色转换为 HSV?

标签 c# colors rgb hsv

如何使用 C# 将 RGB 颜色转换为 HSV?
我一直在寻找一种不使用任何外部库的快速方法。

最佳答案

请注意,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# 代码就是您想要的。它使用 Wikipedia 中描述的算法在 RGB 和 HSV 之间转换. hue 的范围是 0 - 360,saturationvalue 的范围是 0 - 1。

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);
}

关于c# - 如何将 RGB 颜色转换为 HSV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/359612/

相关文章:

C 从位图中读取颜色

python - 在魔杖中获取图像的平均 rgb 值

c# - 使异步代码可取消

c# - 如何为动态添加的按钮创建方法。 ASP.NET C#

c# - C# 中的 Jack Sensing

iphone - iPhone 上的 OpenGL 渐变填充看起来有条纹

android - 设置微调器背景的颜色(共享微调器)

excel - 使用 HSL 功能时如何修复 "Sub or Function not defined"

java - image.getRGB(x,y) 的二进制 AND (&) 运算;

c# - global.asax 中的 Application_Error 真的是处理错误的方法吗?