Last active
December 4, 2024 19:07
-
-
Save RupertAvery/01a7e21289af1ff2d4105fa7de168927 to your computer and use it in GitHub Desktop.
Color Conversion RGB to/from HSL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ColorConverter | |
{ | |
public static (int hue, int saturation, int luminance) RGBToHSL(int red, int green, int blue) | |
{ | |
float r = (red / 255.0f); | |
float g = (green / 255.0f); | |
float b = (blue / 255.0f); | |
float min = Math.Min(Math.Min(r, g), b); | |
float max = Math.Max(Math.Max(r, g), b); | |
float delta = max - min; | |
float L = (max + min) / 2; | |
float H; | |
float S; | |
if (delta == 0) | |
{ | |
H = 0; | |
S = 0.0f; | |
} | |
else | |
{ | |
S = (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; | |
H = (int)(hue * 360); | |
} | |
return ((int)H, (int)(S * 100), (int)(L * 100)); | |
} | |
public static (byte r, byte g, byte b) HSLToRGB(int h, int s, int l) | |
{ | |
byte r = 0; | |
byte g = 0; | |
byte b = 0; | |
var H = (float)h; | |
var S = s / 100f; | |
var L = l / 100f; | |
if (S == 0) | |
{ | |
r = g = b = (byte)(L * 255); | |
} | |
else | |
{ | |
float v1, v2; | |
float hue = (float)H / 360; | |
v2 = (L < 0.5) ? (L * (1 + S)) : ((L + S) - (L * S)); | |
v1 = 2 * L - v2; | |
r = (byte)(255 * HueToRGB(v1, v2, hue + (1.0f / 3))); | |
g = (byte)(255 * HueToRGB(v1, v2, hue)); | |
b = (byte)(255 * HueToRGB(v1, v2, hue - (1.0f / 3))); | |
} | |
return (r, g, b); | |
} | |
private static float HueToRGB(float v1, float v2, float vH) | |
{ | |
if (vH < 0) | |
vH += 1; | |
if (vH > 1) | |
vH -= 1; | |
if ((6 * vH) < 1) | |
return (v1 + (v2 - v1) * 6 * vH); | |
if ((2 * vH) < 1) | |
return v2; | |
if ((3 * vH) < 2) | |
return (v1 + (v2 - v1) * ((2.0f / 3) - vH) * 6); | |
return v1; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment