如何获得8位颜色?

Vla*_*lad 4 java colors 8-bit

所以,此时,我得到了一个生成3个随机整数的方法,从0到255.

我使用3个整数来表示颜色.红色,绿色,蓝色.

所以,在这个时刻,如果我想用生成的颜色设置某些东西的颜色,我使用这个:

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

我需要做的是将3个整数或最终强度值转换为8位整数.

任何形式的文档或指导都非常感谢!

如果需要更多信息,我将评论或修改问题的正文.

小智 8

您可以通过以下方式对颜色进行编码:

Bits    0### 1### 2### 3### 4### 5### 6### 7###
        Alpha---- Red------ Green---- Blue-----
Run Code Online (Sandbox Code Playgroud)

请注意,您将丢失大量有关颜色的信息(但我认为这是您想要的).

为了编码你需要做的事情:

  • 改变颜色范围(0-2550-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);
  }
}
Run Code Online (Sandbox Code Playgroud)

说明

编码

让我们从一个示例颜色开始:new Color(200, 59, 148, 72).现在我们将它转​​换为整数.颜色的二进制表示是:

Alpha 200 -- 11001000
Red    59 -- 00111011
Green 148 -- 10010100
Blue   72 -- 01001000
Run Code Online (Sandbox Code Playgroud)

现在,我们将它们向右移动6位(所以我们得到前2位):

Alpha 3 -- 11
Red   0 -- 00
Green 2 -- 10
Blue  1 -- 01
Run Code Online (Sandbox Code Playgroud)

现在我们把它们放在一起:

Bits  [ 1 ][ 1 ][ 0 ][ 0 ][ 1 ][ 0 ][ 0 ][ 1 ] -- 209
       ALPHA---  RED-----  GREEN---  BLUE----
Run Code Online (Sandbox Code Playgroud)

是的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)
Run Code Online (Sandbox Code Playgroud)

现在我们将它们乘以64:

3 * 64 = 192 (Alpha)
0 * 64 =   0 (Red)
2 * 64 = 128 (Green)
1 * 64 =  64 (Blue)
Run Code Online (Sandbox Code Playgroud)

然后把它们放回一个Color物体里.如您所见,颜色不同:有关颜色的一些信息在此过程中丢失了.这称为有损压缩.