public static HueSaturationValue ColorToHSV(Color color) { HueSaturationValue hsv = new HueSaturationValue(); float min, max, delta; float r = (float)color.R / 255.0f; float g = (float)color.G / 255.0f; float b = (float)color.B / 255.0f; min = Math.Min(r, g); min = Math.Min(min, b); max = Math.Max(r, g); max = Math.Max(max, b); hsv.V = max; // v delta = max - min; if (max != 0) { hsv.S = delta / max; // s } else { // r = g = b = 0 // s = 0, v is undefined hsv.S = 0; hsv.H = -1; return(hsv); } if (r == max) { hsv.H = (g - b) / delta; // between yellow & magenta } else if (g == max) { hsv.H = 2 + (b - r) / delta; // between cyan & yellow } else { hsv.H = 4 + (r - g) / delta; // between magenta & cyan } hsv.H *= 60; // degrees if (hsv.H < 0) { hsv.H += 360; } return(hsv); }
public static Color HSVToColor(HueSaturationValue hsv) { if (hsv.H == 0 && hsv.S == 0) { return(new Color(hsv.V, hsv.V, hsv.V)); } float c = hsv.S * hsv.V; float x = c * (1 - Math.Abs(hsv.H % 2 - 1)); float m = hsv.V - c; if (hsv.H < 1) { return(new Color(c + m, x + m, m)); } else if (hsv.H < 2) { return(new Color(x + m, c + m, m)); } else if (hsv.H < 3) { return(new Color(m, c + m, x + m)); } else if (hsv.H < 4) { return(new Color(m, x + m, c + m)); } else if (hsv.H < 5) { return(new Color(x + m, m, c + m)); } else { return(new Color(c + m, m, x + m)); } }