Converting 8 bit color into RGB value

前端 未结 2 1480
长情又很酷
长情又很酷 2020-12-17 00:07

I\'m implementing global illumination in my game engine with \"reflective shadow maps\". RSM has i.a. color texture. To save memory. I\'m packing 24 bit value into 8 bit val

相关标签:
2条回答
  • 2020-12-17 00:11

    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.

    0 讨论(0)
  • 2020-12-17 00:30

    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
    
    0 讨论(0)
提交回复
热议问题