Calculates the hue component based on R,G,B - Java 2D Graphics

Java examples for 2D Graphics:Color

Description

Calculates the hue component based on R,G,B

Demo Code


import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main{
    public static void main(String[] argv) throws Exception{
        double r = 2.45678;
        double g = 2.45678;
        double b = 2.45678;
        System.out.println(getHue(r,g,b));
    }//from w ww . j  av a  2 s  . c om
    /**
     * Calculates the hue component based on R,G,B
     * @param r
     * @param g
     * @param b
     * @return
     */
    public static double getHue(double r, double g, double b) {
        double M = ColourUtil.max(r, g, b), m = ColourUtil.min(r, g, b), C = M
                - m, hh = -1; //Error value

        if (C == 0) {
            hh = 0;
        } else if (M == r) {
            hh = ((g - b) / C) % 6;
        } else if (M == g) {
            hh = ((b - r) / C) + 2;
        } else if (M == b) {
            hh = ((r - g) / C) + 4;
        }

        return hh / 6;
    }
    /**
     * Returns the maximum value of some list of doubles.
     * @param vals
     * @return
     */
    public static final double max(double... vals) {
        double max = Double.MIN_VALUE;

        for (double v : vals)
            if (v > max)
                max = v;

        return max;
    }
    /**
     * Returns the minimum value of some list of doubles.
     * @param vals
     * @return
     */
    public static final double min(double... vals) {
        double min = Double.MAX_VALUE;

        for (double v : vals)
            if (v < min)
                min = v;

        return min;
    }
}

Related Tutorials