HSV color value to RGB color value - Java 2D Graphics

Java examples for 2D Graphics:Color RGB

Description

HSV color value to RGB color value

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        float h = 2.45678f;
        float s = 2.45678f;
        float v = 2.45678f;
        System.out.println(java.util.Arrays.toString(HSVtoRGB(h, s, v)));
    }/*from   ww  w .j a  va 2 s.  c o m*/

    public static float[] HSVtoRGB(float h, float s, float v) {
        // H is given on [0->6] or -1. S and V are given on [0->1].
        // RGB are each returned on [0->1].
        float m, n, f;
        int i;

        float[] hsv = new float[3];
        float[] rgb = new float[3];

        hsv[0] = h;
        hsv[1] = s;
        hsv[2] = v;

        if (hsv[0] == -1) {
            rgb[0] = rgb[1] = rgb[2] = hsv[2];
            return rgb;
        }
        i = (int) (Math.floor(hsv[0]));
        f = hsv[0] - i;
        if (i % 2 == 0) {
            f = 1 - f; // if i is even
        }
        m = hsv[2] * (1 - hsv[1]);
        n = hsv[2] * (1 - hsv[1] * f);
        switch (i) {
        case 6:
        case 0:
            rgb[0] = hsv[2];
            rgb[1] = n;
            rgb[2] = m;
            break;
        case 1:
            rgb[0] = n;
            rgb[1] = hsv[2];
            rgb[2] = m;
            break;
        case 2:
            rgb[0] = m;
            rgb[1] = hsv[2];
            rgb[2] = n;
            break;
        case 3:
            rgb[0] = m;
            rgb[1] = n;
            rgb[2] = hsv[2];
            break;
        case 4:
            rgb[0] = n;
            rgb[1] = m;
            rgb[2] = hsv[2];
            break;
        case 5:
            rgb[0] = hsv[2];
            rgb[1] = m;
            rgb[2] = n;
            break;
        }

        return rgb;

    }
}

Related Tutorials