Convert an RGB (or RGBA) value back to a Color . - Java 2D Graphics

Java examples for 2D Graphics:Color RGB

Description

Convert an RGB (or RGBA) value back to a Color .

Demo Code

// The MIT License(MIT)

public class Main{
    public static void main(String[] argv) throws Exception{
        int rgb = 2;
        System.out.println(RGBToColor(rgb));
    }/*from   w  ww  .  j a  va2 s  .  c om*/
    /**
     * <p>
     * Convert an RGB (or RGBA) value back to a {@link Color}.
     * </p>
     *
     * <p>
     * The input value should represent a color in the following format:
     * Bits 0-7 are blue, bits 8-15 are green, bits 16-23 are red, and bits 24-31 are alpha.
     * </p>
     *
     * @param rgb The input RGB(A) value.
     * @return A color constructed from the RGB(A) value.
     */
    public static Color RGBToColor(int rgb) {
        int r32 = (rgb >> 16) & 0xFF;
        int g32 = (rgb >> 8) & 0xFF;
        int b32 = (rgb) & 0xFF;
        int a32 = (rgb >> 24) & 0xFF;

        float r = (1f / 255) * r32;
        float g = (1f / 255) * g32;
        float b = (1f / 255) * b32;
        float a = (1f / 255) * a32;

        return new Color(r, g, b, a);
    }
}

Related Tutorials