Java HSL Color Convert hslToRGB(int h, float s, float l)

Here you can find the source of hslToRGB(int h, float s, float l)

Description

hsl To RGB

License

Open Source License

Declaration

public static float[] hslToRGB(int h, float s, float l) 

Method Source Code

//package com.java2s;
/*!/*ww  w  .j  a v a2s. com*/
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2002-2013 Pentaho Corporation..  All rights reserved.
*/

public class Main {
    private static final float ONE_THIRD = 1f / 3f;

    public static float[] hslToRGB(int h, float s, float l) {
        final int hue = normalizeHue(h);

        float saturation = s;
        if (saturation > 100) {
            saturation = 100;
        }
        if (saturation < 0) {
            saturation = 0;
        }
        float lightness = l;
        if (lightness > 100) {
            lightness = 100;
        }
        if (lightness < 0) {
            lightness = 0;
        }
        float m2;
        if (lightness <= 0.5) {
            m2 = lightness * (saturation + 1);
        } else {
            m2 = lightness + saturation - lightness * saturation;
        }
        float m1 = lightness * 2 - m2;

        float r = hueToRGB(m1, m2, hue + ONE_THIRD);
        float g = hueToRGB(m1, m2, hue);
        float b = hueToRGB(m1, m2, hue - ONE_THIRD);
        return new float[] { r, g, b };

    }

    private static int normalizeHue(final int integerValue) {
        return ((integerValue % 360) + 360) % 360;
    }

    private static float hueToRGB(float m1, float m2, float h) {
        if (h < 0) {
            h = h + 1;
        }
        if (h > 1) {
            h = h - 1;
        }
        if ((h * 6f) < 1) {
            return m1 + (m2 - m1) * h * 6;
        }
        if ((h * 2f) < 1) {
            return m2;
        }
        if ((h * 3f) < 2) {
            return m1 + (m2 - m1) * (2 * ONE_THIRD - h) * 6;
        }
        return m1;
    }
}

Related

  1. HSLtoRGB(float h, float s, float l)
  2. HslToRgb(float h, float s, float l, float a)
  3. HSLtoRGB(float hue, float sat, float lum)
  4. hslToRgb(float[] hsl)
  5. HSLtoRGB(float[] hsl)
  6. hueFromColor(Color c)