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 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