Converts from a Color to HSV values (double) - CSharp System.Drawing

CSharp examples for System.Drawing:Color Convert

Description

Converts from a Color to HSV values (double)

Demo Code


using System.Windows.Media;
using System.Globalization;
using System;/*from ww  w.jav a 2  s .com*/

public class Main{
        /// <summary>
        /// Converts from a <see cref="Color"/> to HSV values (double)
        /// </summary>
        /// <param name="color">
        /// </param>
        /// <returns>
        /// Array of [Hue,Saturation,Value] in the range [0,1]
        /// </returns>
        public static double[] ColorToHsv(Color color)
        {
            byte r = color.R;
            byte g = color.G;
            byte b = color.B;

            double h = 0, s, v;

            double min = Math.Min(Math.Min(r, g), b);
            v = Math.Max(Math.Max(r, g), b);
            double delta = v - min;

            if (v == 0.0)
            {
                s = 0;
            }
            else
            {
                s = delta / v;
            }

            if (s == 0)
            {
                h = 0.0;
            }
            else
            {
                if (r == v)
                {
                    h = (g - b) / delta;
                }
                else if (g == v)
                {
                    h = 2 + (b - r) / delta;
                }
                else if (b == v)
                {
                    h = 4 + (r - g) / delta;
                }

                h *= 60;
                if (h < 0.0)
                {
                    h = h + 360;
                }
            }

            var hsv = new double[3];
            hsv[0] = h / 360.0;
            hsv[1] = s;
            hsv[2] = v / 255.0;
            return hsv;
        }
}

Related Tutorials