Code archives/Graphics/HSL and RGB conversion
This code has been declared by its author to be Public Domain code.
Download source code
| Two functions, one to convert from HSL to RGB and one to convert from RGB to HSL. Each takes three integers (as in Color() ) and returns one integer (as in ReadPixel() ). Copied (and translated!) from Wikipedia's article on HSL and HSV. |
Function HSLtoRGB(H,S,L) hk#=H/255.0 sk#=S/255.0 lk#=L/255.0 If lk<0.5 Then q#=lk*(1+sk):Else q#=lk+sk-(lk*sk) p#=2*lk-q tR#=hk+0.3333:If tR>1 Then tR=tR-1 tG#=hk tB#=hk-0.3333:If tB<0 Then tB=tB+1 cR#=p:cG#=p:cB#=p If tR<0.1666 Then cR=p+((q-p)*6*tR) If tG<0.1666 Then cG=p+((q-p)*6*tG) If tB<0.1666 Then cB=p+((q-p)*6*tB) If tR<0.5 And tR>=0.1666 Then cR=q If tG<0.5 And tG>=0.1666 Then cG=q If tB<0.5 And tB>=0.1666 Then cB=q If tR<0.6666 And tR>=0.5 Then cR=p+((q-p)*6*(0.6666-tR)) If tG<0.6666 And tG>=0.5 Then cG=p+((q-p)*6*(0.6666-tG)) If tB<0.6666 And tB>=0.5 Then cB=p+((q-p)*6*(0.6666-tB)) R=255*cR:G=255*cG:B=255*cB Return (R Shl 16) Or (G Shl 8) Or B; Or $FF000000 ;If you want an alpha value as well, add it here End Function Function RGBtoHSL(R,G,B) rk#=R/255.0:gk#=G/255.0:bk#=B/255.0 max#=rk:min#=gk If gk>max Then max=gk If bk>max Then max=bk If rk<min Then min=rk If bk<min Then min=bk If max=min h#=0:s#=0:l#=max Else If max=rk Then h#=(60*(gk-bk)/(max-min)) Mod 360 If max=gk Then h#=(60*(bk-rk)/(max-min)) + 120 If max=bk Then h#=(60*(rk-gk)/(max-min)) + 240 l#=(max+min)/2 If l#<=0.5 Then s#=(max-min)/(2*l) If l#>0.5 Then s#=(max-min)/(2-2*l) EndIf hv=(h/360.0)*255:sv=s*255:lv=l*255 HSL=(hv Shl 16) Or (sv Shl 8) Or lv; Or $FF000000 ;If you want an alpha value as well, add it here Return HSL End Function |