Java RGB Color Convert To RGBtoHSL(int r, int g, int b)

Here you can find the source of RGBtoHSL(int r, int g, int b)

Description

Converts RGB to HSL.

License

LGPL

Parameter

Parameter Description
r red value
g green value
b blue value

Return

Array containing HSL values in the format {h,s,l}

Declaration

public static double[] RGBtoHSL(int r, int g, int b) 

Method Source Code

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

public class Main {
    /**//from www .  j ava 2  s .  com
     * Converts RGB to HSL.
     * HSL values are in decimal form: <br>
     * H: 360 = 1, <br>
     * S: 100 = 1, <br>
     * L: 100 = 1. <br>
     * Thanks to http://serennu.com/colour/rgbtohsl.php for help on this calculation.
     *
     * @param r red value
     * @param g green value
     * @param b blue value
     * @return Array containing HSL values in the format {h,s,l}
     */
    public static double[] RGBtoHSL(int r, int g, int b) {
        double h = 0;
        double s = 0;
        double l = 0;

        double varR = r / 255.0;
        double varG = g / 255.0;
        double varB = b / 255.0;

        double varMin = Math.min(varR, Math.min(varG, varB));
        double varMax = Math.max(varR, Math.max(varG, varB));
        double delMax = varMax - varMin;

        l = (varMin + varMax) / 2;
        if (delMax == 0) {
            h = 0;
            s = 0;
        } else {
            if (l < 0.5) {
                s = delMax / (varMax + varMin);
            } else {
                s = delMax / (2 - varMax - varMin);
            }

            double delR = (((varMax - varR) / 6.0) + (delMax / 2.0)) / delMax;
            double delG = (((varMax - varG) / 6.0) + (delMax / 2.0)) / delMax;
            double delB = (((varMax - varB) / 6.0) + (delMax / 2.0)) / delMax;

            if (varR == varMax) {
                h = delB - delG;
            } else if (varG == varMax) {
                h = (1.0 / 3.0) + delR + delB;
            } else if (varB == varMax) {
                h = (2.0 / 3.0) + delG - delR;
            }

            if (h < 0) {
                h += 1;
            }

            if (h > 1) {
                h -= 1;
            }
        }

        double[] hsl = new double[3];
        hsl[0] = h;
        hsl[1] = s;
        hsl[2] = l;
        return hsl;
    }
}

Related

  1. RGBtoHSB(int red, int green, int blue, float hsb[])
  2. rgbToHsl(byte red, byte green, byte blue)
  3. RgbToHsl(float r, float g, float b, float a)
  4. rgbToHsl(float[] rgb)
  5. RGBtoHSL(int r, int g, int b)
  6. RGBtoHSL(int r, int g, int b, float[] hsl)
  7. rgbToHsl(int red, int green, int blue)
  8. rgbToHsv(byte[] rgb, float[] hsv)
  9. RGBtoHSV(double r, double g, double b)