Java Hex Calculate toHex(int r, int g, int b)

Here you can find the source of toHex(int r, int g, int b)

Description

Returns a web browser-friendly HEX value representing the colour in the default sRGB ColorModel.

License

Open Source License

Parameter

Parameter Description
r red
g green
b blue

Return

a browser-friendly HEX value

Declaration

public static String toHex(int r, int g, int b) 

Method Source Code

//package com.java2s;
/*//w ww  .j  a  va  2 s  .co m
 * SLD Editor - The Open Source Java SLD Editor
 *
 * Copyright (C) 2016, SCISYS UK Limited
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Returns a web browser-friendly HEX value representing the colour in the default sRGB
     * ColorModel.
     * <p>Returns null if r,g,b and inputs are not in the range 0-255.
     *
     * @param r red
     * @param g green
     * @param b blue
     * @return a browser-friendly HEX value
     */
    public static String toHex(int r, int g, int b) {
        if ((r >= 0) && (r <= 255) && (g >= 0) && (g <= 255) && (b >= 0) && (b <= 255)) {
            return "#" + toBrowserHexValue(r) + toBrowserHexValue(g) + toBrowserHexValue(b);
        } else {
            return null;
        }
    }

    /**
     * To browser hex value.
     *
     * @param number the number
     * @return the string
     */
    private static String toBrowserHexValue(int number) {
        StringBuilder builder = new StringBuilder(Integer.toHexString(number & 0xff));
        while (builder.length() < 2) {
            builder.insert(0, "0");
        }
        return builder.toString().toUpperCase();
    }
}

Related

  1. toHex(int n, int bytes)
  2. toHex(int n, int s)
  3. toHex(int nibble)
  4. toHex(int num)
  5. toHex(int nybble)
  6. toHex(int r, int g, int b)
  7. toHex(int r, int g, int b)
  8. toHex(int v)
  9. toHex(int val)