RGB To HSL

This algorithm converts RGB color model to HSL color model.



									struct RGB
{
	unsigned char R;
	unsigned char G;
	unsigned char B;
};

struct HSL
{
	int H;
	float S;
	float L;
};

float Min(float a, float b) {
	return a <= b ? a : b;
}

float Max(float a, float b) {
	return a >= b ? a : b;
}

struct HSL RGBToHSL(struct RGB rgb) {
	struct HSL hsl;

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

	float min = Min(Min(r, g), b);
	float max = Max(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

									struct RGB data = { 82, 0, 87 };
struct HSL value = RGBToHSL(data);
								


Output

									H: 296
S: 1
L: 0.17058824f