Java Hex Convert To convertHexColorToRgb(final String hex)

Here you can find the source of convertHexColorToRgb(final String hex)

Description

Convert a String hex color in #FFF or #FFFFFF format, returning an array of 3 integers representing the corresponding RGB color (in this order).

License

Apache License

Parameter

Parameter Description
hex a parameter

Declaration

public static Integer[] convertHexColorToRgb(final String hex) 

Method Source Code

//package com.java2s;
/*//w w w.  j  a  v a2 s  .  c o  m
 * Licensed to Diennea S.r.l. under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. Diennea S.r.l. 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.
 */

public class Main {
    /**
     * Convert a String hex color in #FFF or #FFFFFF format, returning an array of 3 integers representing the
     * corresponding RGB color (in this order).
     *
     * @param hex
     * @return
     */
    public static Integer[] convertHexColorToRgb(final String hex) {
        if (!hex.matches("^#[abcdefABCDEF0-9]{6}|#[abcdefABCDEF0-9]{3}")) {
            return new Integer[] {};
        }
        final String hexCode;
        if (hex.length() == 4) {
            char[] chars = hex.toCharArray();
            char[] normalizedChars = new char[] { '#', chars[1], chars[1], chars[2], chars[2], chars[3], chars[3] };
            hexCode = new String(normalizedChars);
        } else {
            hexCode = hex;
        }
        return new Integer[] { Integer.valueOf(hexCode.substring(1, 3), 16),
                Integer.valueOf(hexCode.substring(3, 5), 16), Integer.valueOf(hexCode.substring(5, 7), 16) };
    }
}

Related

  1. convertHex(char c)
  2. convertHexa(String bool)
  3. convertHexadecimal2RGB(final String hexColor, final String divider)
  4. convertHexByteToTelcoChar(byte byteValue)
  5. convertHexChars(final String value)
  6. convertHexFloatingPointLiteralToBits(char[] source)
  7. convertHexLong(String hex)
  8. convertHexStringToBinary(String hexString)
  9. convertHexTime2Binary(String timespan)