RGB To HSL

This algorithm converts RGB color model to HSL color model.



									public struct RGB
{
	private byte _r;
	private byte _g;
	private byte _b;

	public RGB(byte r, byte g, byte b)
	{
		this._r = r;
		this._g = g;
		this._b = b;
	}

	public byte R
	{
		get { return this._r; }
		set { this._r = value; }
	}

	public byte G
	{
		get { return this._g; }
		set { this._g = value; }
	}

	public byte B
	{
		get { return this._b; }
		set { this._b = value; }
	}

	public bool Equals(RGB rgb)
	{
		return (this.R == rgb.R) && (this.G == rgb.G) && (this.B == rgb.B);
	}
}

public struct HSL
{
	private int _h;
	private float _s;
	private float _l;

	public HSL(int h, float s, float l)
	{
		this._h = h;
		this._s = s;
		this._l = l;
	}

	public int H
	{
		get { return this._h; }
		set { this._h = value; }
	}

	public float S
	{
		get { return this._s; }
		set { this._s = value; }
	}

	public float L
	{
		get { return this._l; }
		set { this._l = value; }
	}

	public bool Equals(HSL hsl)
	{
		return (this.H == hsl.H) && (this.S == hsl.S) && (this.L == hsl.L);
	}
}

public static HSL RGBToHSL(RGB rgb)
{
	HSL hsl = new HSL();

	float r = (rgb.R / 255.0f);
	float g = (rgb.G / 255.0f);
	float b = (rgb.B / 255.0f);

	float min = Math.Min(Math.Min(r, g), b);
	float max = Math.Max(Math.Max(r, g), b);
	float delta = max - min;

	hsl.L = (max + min) / 2;

	if (delta == 0)
	{
		hsl.H = 0;
		hsl.S = 0.0f;
	}
	else
	{
		hsl.S = (hsl.L <= 0.5) ? (delta / (max + min)) : (delta / (2 - max - min));

		float hue;

		if (r == max)
		{
			hue = ((g - b) / 6) / delta;
		}
		else if (g == max)
		{
			hue = (1.0f / 3) + ((b - r) / 6) / delta;
		}
		else
		{
			hue = (2.0f / 3) + ((r - g) / 6) / delta;
		}

		if (hue < 0)
			hue += 1;
		if (hue > 1)
			hue -= 1;

		hsl.H = (int)(hue * 360);
	}

	return hsl;
}
								


Example

									RGB data = new RGB(82, 0, 87);
HSL value = RGBToHSL(data);
								


Output

									H: 296
S: 1
L: 0.17058824f