Return to Level1Techs.com

HSL and RGB Conversion Algorithms?


#1

Hello,

I’m here ripping my hair out trying to find HSL to RGB and RGB to HSL conversion functions in C. Can anybody who has these functions please reply with them. And I need those that actually work. Not those that somewhat work and return one less or one too much in for example Red value.


#2

https://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion has a javascript version, which is easily convertible to vanilla c:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

typedef struct _RGB { unsigned char r; unsigned char g; unsigned char b; } RGB; 

float huetoColor(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;
}

RGB HSLtoRGB(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 = huetoColor(p, q, h + 1.0f/3.0f);
    g = huetoColor(p, q, h);
    b = huetoColor(p, q, h - 1.0f/3.0f);
  }


  rgb.r = round(r * 0xff); rgb.g = round(g * 0xff); rgb.b = round(b * 0xff); 
  return rgb;
}

which you can call as:

int main(int argc, char * argv[]) {

  RGB rgb = HSLtoRGB(279, 1.00f, 0.22f);

  printf("r = %3i g = %3i b = %3i\n", rgb.r, rgb.g, rgb.b);
  printf("%.2x%.2x%.2x\n", rgb.r, rgb.g, rgb.b);

  return 0;
}

HSLtoRGB takes a signed integral degree and expects floating point s and l values between 0 and 1.0.

Which I compiled as:

clang hsltorgb.c -lm -o hsltorgb.c

with output:

r = 73 g = 0 b = 112
490070

#3

Thank you so fucking much.

I love it when users on forums fucking give better algorithms like this like what?

Yeah but thanks!!


#4

I also made this: https://gist.github.com/FullNitrous/31ac438d40d23ee314a58171c0b4ff81.

You are attributed


#5

I also went ahead and converted the rgb to hsl to C: https://gist.github.com/FullNitrous/7af4970c67d0c75e88b4736fc95dbbba