Convert an RGB color value to a grayscale from 0 to 100. - Java 2D Graphics

Java examples for 2D Graphics:Color RGB

Description

Convert an RGB color value to a grayscale from 0 to 100.

Demo Code

/*/*from www  .  jav a2s  .c  o  m*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int rgb = 2;
        System.out.println(convertToGray(rgb));
    }

    /**
     * Convert an RGB color value to a grayscale from 0 to 100.
     * 
     * @param r
     *            the red component
     * @param g
     *            the green component
     * @param b
     *            the blue component
     * @return the gray value
     */
    public static int convertToGray(final int r, final int g, final int b) {
        return (r * 30 + g * 59 + b * 11) / 100;
    }

    /**
     * Convert an RGB color value to a grayscale from 0 to 100.
     * 
     * @param rgb
     *            the RGB value
     * @return the gray value
     */
    public static int convertToGray(final int rgb) {
        final int r = (rgb & 0xFF0000) >> 16;
        final int g = (rgb & 0xFF00) >> 8;
        final int b = rgb & 0xFF;
        return convertToGray(r, g, b);
    }
}

Related Tutorials