Java RGB Color Convert To rgbToHsv(int rgb)

Here you can find the source of rgbToHsv(int rgb)

Description

Converts the red, green and blue color model to the hue, saturation and value color model

License

Apache License

Parameter

Parameter Description
rgb a parameter

Return

A 3-length array containing hue, saturation and value, in that order. Hue is an integer between 0 and 359, or -1 if it is undefined. Saturation and value are both integers between 0 and 100

Declaration

public static int[] rgbToHsv(int rgb) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/* ww w  . j a v a  2s . c  o m*/
     * Converts the red, green and blue color model to the hue, saturation and
     * value color model
     * 
     * @param rgb
     * @return A 3-length array containing hue, saturation and value, in that
     *         order. Hue is an integer between 0 and 359, or -1 if it is
     *         undefined. Saturation and value are both integers between 0 and
     *         100
     */
    public static int[] rgbToHsv(int rgb) {
        // Source: en.wikipedia.org/wiki/HSV_and_HSL#Formal_derivation
        float r = (float) ((rgb & 0xff0000) >> 16) / 255;
        float g = (float) ((rgb & 0x00ff00) >> 8) / 255;
        float b = (float) (rgb & 0x0000ff) / 255;
        float M = r > g ? (r > b ? r : b) : (g > b ? g : b);
        float m = r < g ? (r < b ? r : b) : (g < b ? g : b);
        float c = M - m;
        float h;
        if (M == r) {
            h = ((g - b) / c);
            while (h < 0)
                h = 6 - h;
            h %= 6;
        } else if (M == g) {
            h = ((b - r) / c) + 2;
        } else {
            h = ((r - g) / c) + 4;
        }
        h *= 60;
        float s = c / M;
        return new int[] { c == 0 ? -1 : (int) h, (int) (s * 100), (int) (M * 100) };
    }
}

Related

  1. RGBtoHSV(float[] hsv, float[] rgb)
  2. RGBtoHSV(int r, int g, int b, double hsv[])
  3. rgbToHsv(int red, int green, int blue)
  4. RGBtoHSV(int red, int green, int blue)
  5. RGBToHSV(int red, int green, int blue, float[] hsv)
  6. RGBtoHTML(int rgb)
  7. RGBToInt(float[] rgb)
  8. RGBtoInt(int r, int g, int b)
  9. RGBtoInt(int red, int green, int blue)