Skip to content

Instantly share code, notes, and snippets.

@sqybi
Created March 28, 2013 13:33
Show Gist options
  • Save sqybi/5263144 to your computer and use it in GitHub Desktop.
Save sqybi/5263144 to your computer and use it in GitHub Desktop.
Convert RGB color (0-255) to HSL (h: 0-360; s, l: 0-1)
private Tuple<double, double, double> RgbToHsl(Tuple<int, int, int> rgb)
{
int r = rgb.Item1;
int g = rgb.Item2;
int b = rgb.Item3;
double h, s, l;
int max = Math.Max(r, Math.Max(g, b));
int min = Math.Min(r, Math.Min(g, b));
// set h
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;
}
else if (max == g)
{
h = 60.0 * (b - r) / (max - min) + 120;
}
else
{
h = 60.0 * (r - g) / (max - min) + 240;
}
// set l
l = (max + min) * 0.5 / 255;
// set s
if (max + min == 0 || max == min)
{
s = 0;
}
else if (l <= 0.5)
{
s = Convert.ToDouble(max - min) / (max + min);
}
else
{
s = Convert.ToDouble(max - min) / (2 * 255 - (max + min));
}
return Tuple.Create<double, double, double>(h, s, l);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment