UnderwareDESIGN

PlayBASIC => Resources => Source Codes => Topic started by: Alex777 on March 15, 2006, 06:07:07 AM

Title: RGB to HSL
Post by: Alex777 on March 15, 2006, 06:07:07 AM
This routine converts an RGB value to an HSL value (making the colour easier to visualize) and gives the new MaxVal & MinVal statements a workout.

[pbcode]

; ----------------------------------
; convert RGB to HSL
; ----------------------------------

Local r = 235
Local g = 236
Local b = 241
Local RGBValue = RGB(r, g, b)

Cls RGB(255, 255, 255)
BoxC 50, 50, 150, 150, 1, RGBValue

H, S, L = RGB2HSL(RGBValue)

Ink RGB(8, 8, 8)
Text 0, 0, "RGB = " + Str$(r) + "/" + Str$(g) + "/" + Str$(b)
Text 0, 20, "HSL = " + Str$(H) + "/" + Str$(S) + "/" + Str$(L)
Sync
WaitKey

; ------------------------------------------------------------------------------

Psub RGB2HSL(RGBValue)
   RemStart
   convert RGBValue to HSL value
   NOTE: there are different conventions for expressing the Hue value; this
   routine follows the Paint Shop Pro method.  Also, the Hue values are slightly
   inaccurate.
   RemEnd
   
   Local r, g, b, r#, g#, b#, max, min, max#, min#
   
   r = RgbR(RGBValue)
   g = RgbG(RGBValue)
   b = RgbB(RGBValue)
   
   r# = RgbR(RGBValue) / Float(255)
   g# = RgbG(RGBValue) / Float(255)
   b# = RgbB(RGBValue) / Float(255)
   
   max# = MaxVal#(r#, g#)
   max = MaxVal(r, g)
   max# = MaxVal#(max#, b#)
   max = MaxVal(max, b)
   min# = MinVal#(r#, g#)
   min = MinVal(r, g)
   min# = MinVal#(min#, b#)
   min = MinVal(min, b)
   
   L = (max + min) / 2
   
   If L <= 128
 S# = (max# - min#) / (max# + min#)
   Else
 S# = (max# - min#) / (2 - (max# + min#))
   EndIf

   S = S# * 256

   If max = b
 H = 60 * ((r# - g#) / (max# - min#)) + 170
   ElseIf max = g
 H = 60 * ((b# - r#) / (max# - min#)) + 85
   Else
   ; max = r
 H = 60 * ((g# - b#) / (max# - min#))
   EndIf
   
EndPsub H, S, L

; =============================================================================

[/pbcode]