Search code examples
javaimage-processingcolorsrgbhsb

I need to know details of how java implements the function Color.RGBtoHSB(r, g, b, hsb). Does they normalize r,g,b


I do not know whether Color.RGBtoHSB(r, g, b, hsb) function normalize the r,g,b before converting it to H,S,B or where i can get the java implementation of their built in functions.


Solution

  • Here is the implementation, from Color class source code directly:

    public static float[] RGBtoHSB(int r, int g, int b, float[] hsbvals) {
    float hue, saturation, brightness;
    if (hsbvals == null) {
        hsbvals = new float[3];
    }
        int cmax = (r > g) ? r : g;
    if (b > cmax) cmax = b;
    int cmin = (r < g) ? r : g;
    if (b < cmin) cmin = b;
    
    brightness = ((float) cmax) / 255.0f;
    if (cmax != 0)
        saturation = ((float) (cmax - cmin)) / ((float) cmax);
    else
        saturation = 0;
    if (saturation == 0)
        hue = 0;
    else {
        float redc = ((float) (cmax - r)) / ((float) (cmax - cmin));
        float greenc = ((float) (cmax - g)) / ((float) (cmax - cmin));
        float bluec = ((float) (cmax - b)) / ((float) (cmax - cmin));
        if (r == cmax)
        hue = bluec - greenc;
        else if (g == cmax)
            hue = 2.0f + redc - bluec;
            else
        hue = 4.0f + greenc - redc;
        hue = hue / 6.0f;
        if (hue < 0)
        hue = hue + 1.0f;
    }
    hsbvals[0] = hue;
    hsbvals[1] = saturation;
    hsbvals[2] = brightness;
    return hsbvals;
    }