Is there a built-in C#/.NET System API for HSV to RGB?

Viewed 38206

Is there an API built into the .NET framework for converting HSV to RGB? I didn't see a method in System.Drawing.Color for this, but it seems surprising that there wouldn't be one in the platform.

6 Answers

For this you can use ColorHelper library:

RGB rgb = ColorConverter.HsvToRgb(new HSV(100, 100, 100));

There is no built-in method (I couldn't find it), but here is code that might help you out. (above solutions didn't work for me)

/// <summary>
/// Converts HSV color values to RGB
/// </summary>
/// <param name="h">0 - 360</param>
/// <param name="s">0 - 100</param>
/// <param name="v">0 - 100</param>
/// <param name="r">0 - 255</param>
/// <param name="g">0 - 255</param>
/// <param name="b">0 - 255</param>
private void HSVToRGB(int h, int s, int v, out int r, out int g, out int b)
{
    var rgb = new int[3];

    var baseColor = (h + 60) % 360 / 120;
    var shift = (h + 60) % 360 - (120 * baseColor + 60 );
    var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;
    
    //Setting Hue
    rgb[baseColor] = 255;
    rgb[secondaryColor] = (int) ((Mathf.Abs(shift) / 60.0f) * 255.0f);
    
    //Setting Saturation
    for (var i = 0; i < 3; i++)
        rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));
    
    //Setting Value
    for (var i = 0; i < 3; i++)
        rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);

    r = rgb[0];
    g = rgb[1];
    b = rgb[2];
}

I've searched the internet for better way to do this, but I can't find it.

This is a C# method to convert HSV to RGB, the method arguments are in range of 0-1, the output is in range of 0-255

private Color hsv2rgb (float h, float s, float v)
    {
        Func<float, int> f = delegate (float n)
        {
            float k = (n + h * 6) % 6;
            return (int)((v - (v * s * (Math.Max(0, Math.Min(Math.Min(k, 4 - k), 1))))) * 255);
        };
        return Color.FromArgb(f(5), f(3), f(1));
    }
Related