Java RGB Color Convert To RGBtoHSB(int r, int g, int b, float hsbvals[])

Here you can find the source of RGBtoHSB(int r, int g, int b, float hsbvals[])

Description

Convert from RGB to HSB color

License

Open Source License

Parameter

Parameter Description
r a parameter
g a parameter
b a parameter
hsbvals the array used to return the three HSB values, or null

Return

a float array containing hue, saturation, brightness.

Declaration

public static float[] RGBtoHSB(int r, int g, int b, float hsbvals[]) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2011 MadRobot.//from w  w w  .  j  ava2 s  . co  m
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *  Elton Kent - initial API and implementation
 ******************************************************************************/

public class Main {
    /**
     * Convert from RGB to HSB color
     * 
     * @param r
     * @param g
     * @param b
     * @param hsbvals
     *            the array used to return the three HSB values, or null
     * 
     * @return a float array containing hue, saturation, brightness.
     */
    public static float[] RGBtoHSB(int r, int g, int b, float hsbvals[]) {
        if (hsbvals == null) {
            hsbvals = new float[3];
        }
        int l = r <= g ? g : r;
        if (b > l) {
            l = b;
        }
        int i1 = r >= g ? g : r;
        if (b < i1) {
            i1 = b;
        }
        float f2 = l / 255F;
        float f1;
        if (l != 0) {
            f1 = (float) (l - i1) / (float) l;
        } else {
            f1 = 0.0F;
        }
        float f;
        if (f1 == 0.0F) {
            f = 0.0F;
        } else {
            float f3 = (float) (l - r) / (float) (l - i1);
            float f4 = (float) (l - g) / (float) (l - i1);
            float f5 = (float) (l - b) / (float) (l - i1);
            if (r == l) {
                f = f5 - f4;
            } else if (g == l) {
                f = (2.0F + f3) - f5;
            } else {
                f = (4F + f4) - f3;
            }
            f /= 6F;
            if (f < 0.0F) {
                f++;
            }
        }
        hsbvals[0] = f;
        hsbvals[1] = f1;
        hsbvals[2] = f2;
        return hsbvals;
    }
}

Related

  1. rgbToHex(int r, int g, int b)
  2. RGBtoHex(int r, int g, int b)
  3. rgbToHex(int[] rgb)
  4. RGBToHex(int[] rgb)
  5. rgbToHex(String color)
  6. RGBtoHSB(int r, int g, int b, float[] hsbvals)
  7. RGBtoHSB(int red, int green, int blue, float hsb[])
  8. rgbToHsl(byte red, byte green, byte blue)
  9. RgbToHsl(float r, float g, float b, float a)