Converting 8 bit color into RGB value

∥☆過路亽.° 提交于 2019-11-29 04:38:27

In javascript

Encode

encodedData = (Math.floor((red / 32)) << 5) + (Math.floor((green / 32)) << 2) + Math.floor((blue / 64));

Decode

red = (encodedData >> 5) * 32;
green = ((encodedData & 28) >> 2) * 32;
blue = (encodedData & 3) * 64;

While decoding we are using AND Gate/Operator to extract desired bits and discard leading bits. With green, we would then have to shift right to discard bits at right.

While encoding Math.floor is used to truncate decimal part, if rounded off it would create total value greater than 255 making it a 9 bit number.

UPDATE 1
It does not provide accurate results if we divide color by 32 or 64.

RRRGGGBB

R/G = 3bit, max value is 111 in binary which is 7 in decimal. B = 2bit, max value is 11 in binary which is 3 in decimal.

We should divide R/G by value equal or greater than 255/7 and B by value equal or greater than 255/3. We should also note that in place of Math.floor we should use Math.round because rounding off gives more accurate results.

To convert 8bit [0 - 255] value into 3bit [0, 7], the 0 is not a problem, but remember 255 should be converted to 7, so the formula should be Red3 = Red8 * 7 / 255.

To convert 24bit color into 8bit,

8bit Color = (Red * 7 / 255) << 5 + (Green * 7 / 255) << 2 + (Blue * 3 / 255)

To reverse,

Red   = (Color >> 5) * 255 / 7
Green = ((Color >> 2) & 0x07) * 255 / 7
Blue  = (Color & 0x03) * 255 / 3
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!