RGB-HLS Conversion

From Director Online Wiki
Jump to: navigation, search

Description

Convert an RGB color value to an HLS color value.

Code

-- Lingo Syntax
on RGBtoHLS myRGB
  red   = myRGB.red
  green = myRGB.green
  blue  = myRGB.blue
  maxValue    = 255
  maxRGBValue = max(red, green, blue)
  minRGBValue = min(red, green, blue)
  RGBRange    = maxRGBValue - minRGBValue
  doubleL     = maxRGBValue + minRGBValue
  lightness   = doubleL / 2
  if maxRGBValue  = minRGBValue then
    saturation = 0
    hue        = 0
  else
    if lightness < 128 then
      saturation = (maxValue * RGBRange) / doubleL
    else
      saturation = (maxValue * RGBRange) / ((maxValue * 2) - doubleL)
    end if
    redCorrection   = (maxValue * (maxRGBValue - red))   / RGBRange
    greenCorrection = (maxValue * (maxRGBValue - green)) / RGBRange
    blueCorrection  = (maxValue * (maxRGBValue - blue))  / RGBRange
    if red = maxRGBValue then
      hue = blueCorrection - greenCorrection
    else if green = maxRGBValue then
      hue = (2 * maxValue) + redCorrection - blueCorrection
    else if blue = maxRGBValue then
      hue = (4 * maxValue) + greenCorrection - redCorrection
    end if
    hue = 60 * hue / maxValue
    if hue < 0 then hue = hue + 360
  end if
  HLS = [:]
  addProp HLS #hue, hue
  addProp HLS #lightness, lightness
  addProp HLS #saturation, saturation
 
  return HLS
end