将颜色转换为 6 位颜色或从 6 位颜色转换

本文关键字:颜色 转换 | 更新日期: 2023-09-27 18:34:17

我正在尝试将一个字节(6位RGB)转换为适当的System.Drawing.Color结构。我的字节看起来像这样:

 UNUSED
---------------------------------
| 0 | 0 | 1 | 1 | 0 | 0 | 1 | 1 |
---------------------------------
          R1  R2  G1  G2  B1  B2

所以鉴于此:

byte color = 51;

如何将其转换为可以传递到 Color.FromArgb 的最接近的颜色匹配?我知道这可能涉及一些数学公式,但我不知道它是什么。我还需要反过来。我需要将颜色转换为 6 位字节。请为此指出正确的方向。

将颜色转换为 6 位颜色或从 6 位颜色转换

您只需要将 RGB 值乘以 64。

int r = color >> 4;
int g = (color >> 2) & 0x3;
int b = color & 0x3;
Color frameworkColor = Color.FromArgb(r * 64, g * 64, b * 64);

同样,要回到您的 6 位颜色:

int r = frameworkColor.R / 64;
int g = frameworkColor.G / 64;
int b = frameworkColor.B / 64;
int color = (r << 4) | (g << 2) | b;

您将对组件进行定位:

int r = color >> 4;
int g = (color >> 2) & 3
int b = color & 3;

然后,您可以通过乘以 85 将 0..3 值缩放到 0..255 范围:

Color c = Color.FromArgb(255, r * 85, g * 85, b * 85);

要走另一种方式,您将除以 85 并将它们放在一个字节中:

int r = c.R / 85;
int g = c.G / 85;
int b = c.B / 85;
byte color = (byte)((r << 4) + (g << 2) + b);

我会乘以 85 而不是 64,这样 00 映射到 0,而 11 映射到 255。

Color.FromArgb(255, 85 * ((color >> 4) & 3), 85 * ((color >> 2) & 3), 85 * (color & 3))