RGB to HSL Color - CSharp System.Drawing

CSharp examples for System.Drawing:Color RGB

Description

RGB to HSL Color

Demo Code


using Windows.UI;
using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/*from   w  w  w  .  j  a v  a 2s .  c o m*/

public class Main{
        public static HSL RGB2HSL(Color colorToChange)
        {
            double h = 0, s = 0, l = 0;

            double r = colorToChange.R / 255.0;
            double g = colorToChange.G / 255.0;
            double b = colorToChange.B / 255.0;

            double max = Math.Max(r, Math.Max(g, b));
            double min = Math.Min(r, Math.Min(g, b));

            if (max == min)
            {
                h = 0;
            }
            else if (max == r && g >= b)
            {
                h = 60.0 * (g - b) / (max - min);
            }
            else if (max == r && g < b)
            {
                h = (60.0 * (g - b) / (max - min)) + 360.0;
            }
            else if (max == g)
            {
                h = (60.0 * (b - r) / (max - min)) + 120.0;
            }
            else if (max == b)
            {
                h = (60.0 * (r - g) / (max - min)) + 240.0;
            }

            l = (max + min) / 2.0;

            if (l == 0 || max == min)
            {
                s = 0;
            }
            else if (l > 0 && l <= 0.5)
            {
                s = (max - min) / (max + min);
            }
            else if (l > 0.5)
            {
                s = (max - min) / (2 - (max + min)); // (max-min > 0)?
            }

            return new HSL(
                double.Parse(string.Format("{0:0.##}", h)),
                double.Parse(string.Format("{0:0.##}", s)),
                double.Parse(string.Format("{0:0.##}", l))
                );
        }
}

Related Tutorials