Question

I am trying to convert HSL values to RGB but I am getting strange results, if the hue value is about 180 then the resulting RGB is negative dependent on the lightness value.

My implementation:

public class HSLtoRGB {
    private static float hueToRGB(float m1, float m2, float h) {
        if(h < 0) {
            h += 1.0f;
        } else if(h > 1.0f) {
            h -= 1.0f;
        }

        if((h * 6) < 1) {
            return m1 + (m2 - m1) * 6 * h;
        } else if((h * 2) < 1) {
            return m2;
        } else if((h * 3) < 2) {
            return m1 + (m2 - m1) * ((2 / 3) - h) * 6;
        } else {
            return m1;
        }
    }

    public static void main(String[] args) {
        float h = 180.0f / 360.0f;
        float s = 100.0f / 100.0f;
        float l =  38.0f / 100.0f;
        float r = 0;
        float g = 0;
        float b = 0;

        if(s == 0.0) {
            r = g = b = l;
        } else {
            float m2 = l < 0.5 ? l * (1 + s) : (l + s) - (l * s);
            float m1 = (l * 2) - m2;

            r = hueToRGB(m1, m2, h + (1.0f / 3.0f));
            g = hueToRGB(m1, m2, h);
            b = hueToRGB(m1, m2, h - (1.0f / 3.0f));
        }

        System.out.printf("%.2f %.2f %.2f -> %.2f %.2f %.2f",
                          h, s, l,
                          r, g, b);
    }
}

and the output from the above:

0.50 1.00 0.38 -> 0.00 -2.28 0.76

I followed this algorithm and checked many others to get the above formula, including the one in the CSS3 docs:

HOW TO RETURN hsl.to.rgb(h, s, l): 
   SELECT: 
      l<=0.5: PUT l*(s+1) IN m2
      ELSE: PUT l+s-l*s IN m2
   PUT l*2-m2 IN m1
   PUT hue.to.rgb(m1, m2, h+1/3) IN r
   PUT hue.to.rgb(m1, m2, h    ) IN g
   PUT hue.to.rgb(m1, m2, h-1/3) IN b
   RETURN (r, g, b)

HOW TO RETURN hue.to.rgb(m1, m2, h): 
   IF h<0: PUT h+1 IN h
   IF h>1: PUT h-1 IN h
   IF h*6<1: RETURN m1+(m2-m1)*h*6
   IF h*2<1: RETURN m2
   IF h*3<2: RETURN m1+(m2-m1)*(2/3-h)*6
   RETURN m1
Was it helpful?

Solution

It looks like the culprit is this line:

return m1 + (m2 - m1) * ((2 / 3) - h) * 6;

You're doing integer division 2/3, which will equal 0. A simple change to:

return m1 + (m2 - m1) * ((2.0f / 3.0f) - h) * 6;

seems to fix it for me. It comes back with equal blue/green 0.76, which makes sense for hue 180(cyan).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top