Skip to content

Instantly share code, notes, and snippets.

@tcoupin
Created September 29, 2017 10:47
Show Gist options
  • Select an option

  • Save tcoupin/980a0c66442f58dfcdc7184a3d446b3a to your computer and use it in GitHub Desktop.

Select an option

Save tcoupin/980a0c66442f58dfcdc7184a3d446b3a to your computer and use it in GitHub Desktop.
PL/Pgsql function to convert color in HSL to RGB hex code
CREATE OR REPLACE FUNCTION hsl2rvb_hexa(hue float, sat float, light float)
RETURNS text AS $$
declare
c float := sat*light;
tp float := (hue/60.0);
x float := c*((1-abs((tp::int)%2-1))::float);
m float := light-c;
rp float;
vp float;
bp float;
r int;
v int;
b int;
BEGIN
case
when (tp>=0 and tp<1) then
rp=c;
vp=x;
bp=0.;
when (tp>=1 and tp<2) then
rp=x;
vp=c;
bp=0.;
when (tp>=2 and tp<3) then
rp=0.;
vp=c;
bp=x;
when (tp>=3 and tp<4) then
rp=0.;
vp=x;
bp=c;
when (tp>=4 and tp<5) then
rp=x;
vp=0.;
bp=c;
when (tp>=5 and tp<6) then
rp=c;
vp=0.;
bp=x;
else
rp=0.;
vp=0.;
bp=0.;
end case;
r=((rp+m)*255)::int;
v=((vp+m)*255)::int;
b=((bp+m)*255)::int;
return format('#%02s%02s%02s',to_hex(r),to_hex(v),to_hex(b));
END;
$$ LANGUAGE plpgsql;
@mvlijmen
Copy link

mvlijmen commented Nov 3, 2022

Thanks for sharing this. However, I'm a bit confused. HSL 0,100,100 (red) should be ff0000 in hex color space. Your function gives me #639cffd97aacffd97aac. What am I doing wrong?
Kind regards,
Michiel

@mvlijmen
Copy link

mvlijmen commented Nov 3, 2022

BTW my Postgres version is 12.12. Is this too new?

@tcoupin
Copy link
Author

tcoupin commented Nov 4, 2022

Hi, I don't use this since a lot of time!
But I think think that:

  • hue must be in [0;360]
  • sat must be in [0;1]
  • light must be in [0;1]

=> https://en.wikipedia.org/wiki/HSL_and_HSV#To_RGB

@mvlijmen
Copy link

mvlijmen commented Nov 4, 2022 via email

@tcoupin
Copy link
Author

tcoupin commented Nov 4, 2022

yes 25% = 0.25

but take care of conversion between int and float. You need to cast your int to float and then divided it by 100.0

@mvlijmen
Copy link

mvlijmen commented Nov 4, 2022 via email

@mvlijmen
Copy link

mvlijmen commented Nov 7, 2022 via email

@zdila
Copy link

zdila commented Nov 29, 2022

tp must not be converted to int before doing modulo. Instead use this modulo function https://stackoverflow.com/a/53487651/289827

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment