Returns a gray version of the color parameter c, which means all parts (r,g,b) do have the same value. - Java 2D Graphics

Java examples for 2D Graphics:Color

Description

Returns a gray version of the color parameter c, which means all parts (r,g,b) do have the same value.

Demo Code

/*/*from w  w  w. ja  va 2s  .c o  m*/
 * Copyright (c) 2002 and later by MH Software-Entwicklung. All Rights Reserved.
 *  
 * JTattoo is multiple licensed. If your are an open source developer you can use
 * it under the terms and conditions of the GNU General Public License version 2.0
 * or later as published by the Free Software Foundation.
 *  
 * see: gpl-2.0.txt
 * 
 * If you pay for a license you will become a registered user who could use the
 * software under the terms and conditions of the GNU Lesser General Public License
 * version 2.0 or later with classpath exception as published by the Free Software
 * Foundation.
 * 
 * see: lgpl-2.0.txt
 * see: classpath-exception.txt
 * 
 * Registered users could also use JTattoo under the terms and conditions of the 
 * Apache License, Version 2.0 as published by the Apache Software Foundation.
 *  
 * see: APACHE-LICENSE-2.0.txt
 */
//package com.java2s;
import java.awt.Color;

public class Main {
    /**
     * Returns a gray version of the color parameter c, which means all parts (r,g,b) do have the same value.
     * 
     * @param c the color
     * 
     * @return a gray version of the color parameter c.
     */
    public static Color toGray(Color c) {
        if (c == null) {
            return null;
        }

        int gray = getGrayValue(c);
        return new Color(gray, gray, gray, c.getAlpha());
    }

    /**
     * Returns a value between 0 and 255 which represents the gray value of the color parameter. 
     * 
     * @param c the color you want to calculate the gray value
     * 
     * @return the gray value
     */
    public static int getGrayValue(Color c) {
        if (c == null) {
            return 0;
        }

        double r = c.getRed();
        double g = c.getGreen();
        double b = c.getBlue();
        return Math.min(255, (int) (r * 0.28 + g * 0.59 + b * 0.13));
    }

    /**
     * Returns a value between 0 and 255 which represents the median gray value of the color array. 
     * 
     * @param ca the color array you want to calculate the gray value
     * 
     * @return the gray value
     */
    public static int getGrayValue(Color[] ca) {
        int sum = 0;
        for (int i = 0; i < ca.length; i++) {
            sum += getGrayValue(ca[i]);
        }
        return (sum / ca.length);
    }
}

Related Tutorials