How to get 8-bit colors?

So, at this moment I have a method that generates 3 random numbers from 0 to 255.

I use 3 integers for colors.Red, Green, Blue.

So, at this point, if I want to set the color of something, with the generated colors, I use this:

 Color.argb(255, r, g, b); //255 =max intensity and after ,there are red green blue

I need to do to convert 3 integers, or ultimately an intensity value, to an 8-bit integer.

Any documentation or manual is highly appreciated!

If you need more information, I will comment or change the body of the question.

+4
source share
1 answer

You can encode colors as follows:

Bits    0### 1### 2### 3### 4### 5### 6### 7###
        Alpha---- Red------ Green---- Blue-----

, ( , , ).

:

  • (0-255 0-3)
  • , 8- .

:

import java.awt.Color;

abstract class EightBit {
  public static int fromColor(Color c) {
    return ((c.getAlpha() >> 6) << 6)
         + ((c.getRed()   >> 6) << 4)
         + ((c.getGreen() >> 6) << 2)
         +  (c.getBlue()  >> 6);
  }
  public static Color toColor(int i) {
    return new Color(((i >> 4) % 4) * 64,
                     ((i >> 2) % 4) * 64,
                      (i       % 4) * 64,
                      (i >> 6)      * 64);
  }
}

: new Color(200, 59, 148, 72). . :

Alpha 200 -- 11001000
Red    59 -- 00111011
Green 148 -- 10010100
Blue   72 -- 01001000

6 ( 2 ):

Alpha 3 -- 11
Red   0 -- 00
Green 2 -- 10
Blue  1 -- 01

:

Bits  [ 1 ][ 1 ][ 0 ][ 0 ][ 1 ][ 0 ][ 0 ][ 1 ] -- 209
       ALPHA---  RED-----  GREEN---  BLUE----

209. ?

, 8- : 209. . -, 2- , 4:

Bits  [ 1 ][ 1 ][ 0 ][ 0 ][ 1 ][ 0 ][ 0 ][ 1 ]
      \_shift_by_6_bits_____________[ 1 ][ 1 ] -- 3 (Alpha)
                \_by_4_bits_________[ 0 ][ 0 ] -- 0 (Red)
                          \_by_2____[ 1 ][ 0 ] -- 2 (Green)
                   shift by 0 bits: [ 0 ][ 1 ] -- 1 (Blue)

64:

3 * 64 = 192 (Alpha)
0 * 64 =   0 (Red)
2 * 64 = 128 (Green)
1 * 64 =  64 (Blue)

Color. , : . .

+8

All Articles