RGB to HSL - CSharp System.Drawing

CSharp examples for System.Drawing:Color RGB

Description

RGB to HSL

Demo Code


using System.IO;//w  ww.  ja  v  a  2s  .  c om
using System.Drawing.Imaging;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;

public class Main{
        // Given a Color (RGB Struct) in range of 0-255
        // Return H,S,L in range of 0-1
        //code mostly taken from: http://www.geekymonkey.com/Programming/CSharp/RGB2HSL_HSL2RGB.htm
        public static void RGB2HSL(Pixel rgb, out double h, out double s, out double l)
        {
            double r = rgb.Red / 255.0;
            double g = rgb.Green / 255.0;
            double b = rgb.Blue / 255.0;
            double v, m, vm, r2, g2, b2;

            h = 0; // default to black
            s = 0;
            l = 0;
            v = Math.Max(r, g);
            v = Math.Max(v, b);
            m = Math.Min(r, g);
            m = Math.Min(m, b);
            l = (m + v) / 2.0;

            if (l <= 0.0)
                return;

            vm = v - m;
            s = vm;

            if (s > 0.0)
                s /= (l <= 0.5) ? (v + m) : (2.0 - v - m);
            else
                return;

            r2 = (v - r) / vm;
            g2 = (v - g) / vm;
            b2 = (v - b) / vm;

            if (r == v)
                h = (g == m ? 5.0 + b2 : 1.0 - g2);
            else if (g == v)
                h = (b == m ? 1.0 + r2 : 3.0 - b2);
            else
                h = (r == m ? 3.0 + g2 : 5.0 - r2);

            h /= 6.0;
        }
}

Related Tutorials