从 16 位获取颜色

Get a color from 16-bits

我正在研究 C# 中的颜色,我想知道如何从 16 位字节数组中获取颜色值。下面是我使用 32 位字节数组的代码。

                var colorArray = new Color[b.Length/4];                
                for (var i = 0; i < b.Length; i += 4)
                {
                    var color = Color.FromArgb(b[i + 0], b[i + 1], b[i + 2], b[i + 3]);
                    colorArray[i / 4] = color;
                }

您基本上将每个字段的最高有效位以其新格式移动到正确的位置,并将任何缺失的位屏蔽为零。绿色分为两个字节。如果数组是 16 位整数的数组,这会更容易,但如果它是以字节为单位,那么一对字节的位操作大致是这样的。

+----+----+----+----+----+----+---+---+---+---+---+---+---+---+---+---+
|               byte1                 |             byte0             |
+----+----+----+----+----+----+---+---+---+---+---+---+---+---+---+---+
| 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
+----+----+----+----+----+----+---+---+---+---+---+---+---+---+---+---+
| -  |          Red           |       Green       |       Blue        |
+----+----+----+----+----+----+---+---+---+---+---+---+---+---+---+---+

B8 = (byte0 << 3) & 0xF8;
G8 = ((byte1 << 6) & 0xC0) || ((byte0 >> 2) & 0x38);
R8 = (byte1 << 1) & 0xF8;

B8G8R8 = B8 | (G8 << 8) || (R8 << 16);