Skip to content

Instantly share code, notes, and snippets.

@fullnitrous
Created October 20, 2018 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fullnitrous/31ac438d40d23ee314a58171c0b4ff81 to your computer and use it in GitHub Desktop.
Save fullnitrous/31ac438d40d23ee314a58171c0b4ff81 to your computer and use it in GitHub Desktop.
Proper Conversion of HSL color to RGB
/*
HSL to RGB
Compile with: gcc hsl_to_rgb.c -lm -o hsl_to_rgb
Attributions to: cburn11, https://forum.level1techs.com/u/cburn11
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <stdint.h>
struct hsl
{
int h;
float s;
float l;
};
struct rgb
{
uint8_t r;
uint8_t g;
uint8_t b;
};
float hue_to_color(float p, float q, float t)
{
if(t < 0) ++t;
if(t > 1) --t;
if(1.0f / 6.0f > t) return p + (q - p) * 6 * t;
if(0.5f > t) return q;
if(2.0f / 3.0f > t) return p + (q - p) * (2.0f / 3.0f - t) * 6;
return p;
}
struct rgb hsl_to_rgb(int hdeg, float s, float l)
{
float h = abs(hdeg) % 360 / 360.0f;
float r = 0.f, g = 0.f, b = 0.f;
struct rgb rgb;
if(0 == s)
{
r = g = b = l;
}
else
{
float q = l < 0.5f ? l * (1 + s) : l + s - l * s;
float p = 2 * l - q;
r = hue_to_color(p, q, h + 1.0f / 3.0f);
g = hue_to_color(p, q, h);
b = hue_to_color(p, q, h - 1.0f / 3.0f);
}
rgb.r = round(r * 0xff); rgb.g = round(g * 0xff); rgb.b = round(b * 0xff);
return rgb;
}
int main(void)
{
struct hsl input = {123, 0.3f, 0.4f};
struct rgb output = hsl_to_rgb(input.h, input.s, input.l);
printf("\nConverted hsl(%d°, %.2f%%, %.2f%%) to rgb(%d, %d, %d)\n\n",
input.h, input.s * 100, input.l * 100,
output.r, output.g, output.b);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment