Converting from HSV (HSB in Java) to RGB without using java.awt.Color (disallowed on Google App Engine)

前端 未结 7 1203
独厮守ぢ
独厮守ぢ 2020-12-09 12:44

I figured I should post this question, even if I have already found a solution, as a Java implementation was not readily available when I searched for it.

Using HSV

7条回答
  •  醉酒成梦
    2020-12-09 13:17

    The solution was found here: http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/

    Martin Ankerl provides a good post on the subject, and provides Ruby script. For those too busy (or lazy) to implement it in Java, here's the one I did (I am sure it can be written more effectively, please feel free to comment):

    public static String hsvToRgb(float hue, float saturation, float value) {
        float r, g, b;
    
        int h = (int)(hue * 6);
        float f = hue * 6 - h;
        float p = value * (1 - saturation);
        float q = value * (1 - f * saturation);
        float t = value * (1 - (1 - f) * saturation);
    
        if (h == 0) {
            r = value;
            g = t;
            b = p;
        } else if (h == 1) {
            r = q;
            g = value;
            b = p;
        } else if (h == 2) {
            r = p;
            g = value;
            b = t;
        } else if (h == 3) {
            r = p;
            g = q;
            b = value;
        } else if (h == 4) {
            r = t;
            g = p;
            b = value;
        } else if (h <= 6) {
            r = value;
            g = p;
            b = q;
        } else {
            throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + hue + ", " + saturation + ", " + value);
        }
    
        String rs = Integer.toHexString((int)(r * 255));
        String gs = Integer.toHexString((int)(g * 255));
        String bs = Integer.toHexString((int)(b * 255));
        return rs + gs + bs;
    }
    

提交回复
热议问题