C#实现RGB、HSV(HSB)互转

按标准公式计算。

// RGB转HSV
public static void RGB2HSV(int r, int g, int b, out float h, out float s, out float v)
{
    float max = Math.Max(r, Math.Max(g,b));
    float min = Math.Min(r, Math.Min(g,b));

    // 计算hue
    if(min == max) { h = 0;}
    else if(max == r && g >= b)
    {
        h = 60*(g - b) / (max - min);
    }
    else if(max == r && g < b)
    {
        h = 360 + 60 * (g - b) / (max - min);
    }
    else if(max == g)
    {
        h = 120 + 60 * (b - r) / (max - min);
    }
    else
    {
        h = 240 + 60*(r - g) / (max - min);
    }

    // 计算saturation
    if(max==0)
    {
        s = 0;
    }
    else
    {
        s = (max - min) / max;
    }

    // 计算v / brightness
    v = max / 255;
}

// HSV转RGB
public static void HSV2RGB(float h, float s, float v, out int  r, out int g, out int b)
{
    // s,v为小数表示,如0.25表示25
    float hi = (float)(Math.Floor(h/60))%6;
    float f = h / 60 - hi;
    float p = v * (1 - s);
    float q = v * (1 - f * s);
    float t = v * (1 - (1 - f) * s);
    float r0=0, g0=0, b0=0;
    switch ((int)hi)
    {
        case 0:
            r0 = v; g0 = t; b0 = p;
            break;
        case 1:
            r0 = q; g0 = v; b0 = p;
            break;
        case 2:
            r0 = p; g0 = v; b0 = t;
            break;
        case 3:
            r0 = p; g0 = q; b0 = v;
            break;
        case 4:
            r0 = t; g0 = p; b0 = v;
            break;
        case 5:
            r0 = v; g0 = p; b0 = q;
            break;
    }

    // 四舍五入取整
    r = (int)Math.Round(r0*255);
    g = (int)Math.Round(g0*255);
    b = (int)Math.Round(b0*255);

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值