Nick
Nick

Reputation: 45

Converting HSL to RGB

This should take a set an HSL color code and print out its equivalent in RGB.
It should print out 97, 153, 194.
Instead it prints out 0.3808, 0.60153333333333, 0.7592.

function HSL(hue, saturation, lightness, alpha)
    if hue < 0 or hue > 360 then
        return 0, 0, 0, alpha
    end
    if saturation < 0 or saturation > 1 then
        return 0, 0, 0, alpha
    end
    if lightness < 0 or lightness > 1 then
        return 0, 0, 0, alpha
    end
    local chroma = (1 - math.abs(2 * lightness - 1)) * saturation
    local h = hue/60
    local x =(1 - math.abs(h % 2 - 1)) * chroma
    local r, g, b = 0, 0, 0
    if h < 1 then
        r,g,b=chroma,x,0
    elseif h < 2 then
        r,b,g=x,chroma,0
    elseif h < 3 then
        r,g,b=0,chroma,x
    elseif h < 4 then
        r,g,b=0,x,chroma
    elseif h < 5 then
        r,g,b=x,0,chroma
    else
        r,g,b=chroma,0,x
    end
    local m = lightness - chroma/2
    return r+m,g+m,b+m,alpha
end

print(HSL(205, .44, .57))

Upvotes: 1

Views: 3217

Answers (1)

daurnimator
daurnimator

Reputation: 4311

Your function gives values in the range 0-1; multiply by 256 to get it in the range 0-256.

Upvotes: 7

Related Questions