问题
I am trying to convert a decimal value back to an RGB value.
Assuming that this is the formula for compiling the decimal value
c = r*(255*255)+g*255+b
(For example rgb(16,120,78) adds up to 1071078)
How would one solve r, g and b without any "overflow"?
Thanks in advance!
回答1:
Use division, modulo (%) and floor rounding:
var r = Math.floor(c / (256*256));
var g = Math.floor(c / 256) % 256;
var b = c % 256;
Edit:
halex spotted the diffence in use of 255 and 256 in the code. You should (as Millie Smith pointed out) use 256 instead of 255 when you put the components together:
var c = r * (256*256) + g * 256 + b;
A color component can have a value from 0 to 255, so you need to multiply by 256 to keep the next component from overlapping the previous.
回答2:
For starters, your formula for computing the decimal value looks off. 255 isn't a power of 16 (or even 2); if you want to shift a hex digit left, like what multiplying by powers of 10 does under decimal, you want to multiply by 16^n, where n is the number of places to shift it left.
Here's our new RGB to decimal formula:
c = r * 16^4 + g * 16^2 + b
So, supposing we have c, the decimal representation of an RGB color code, we solve for r, g, b:
b = c % 256
g_0 = (c % 65536 - b)
r_0 = c - g_0 - b
g = g_0 / 256
r = r_0 / 65536
These are all integer operations, so they should be fast, but I can't assure you the interpreter will handle them that way. As a function:
function c_to_rgb(c) {
var b = c % 256,
g_0 = (c % 65536 - b),
r_0 = c - g_0 - b,
g = g_0 / 256,
r = r_0 / 65536;
return [r, g, b];
}
回答3:
This Github link helps a lot, but I edited the code with this code to solve a problem with me:
// convert three r,g,b integers (each 0-255) to a single decimal integer (something
between 0 and ~16m)
function colourToNumber(r, g, b) {
return (r << 16) + (g << 8) + (b);
}
// convert it back again (to a string)
function numberToColour(number) {
const r = (number & 0xff0000) >> 16;
const g = (number & 0x00ff00) >> 8;
const b = (number & 0x0000ff);
//return [b, g, r];
return `rgb(${b},${g},${r})`;
}
my edited code make the RGB returns correctly like the color I set
Examples of mine:
color in decimal is: 11665407 this is yellow
color in decimal is: 11665329 this is green
please test booth codes with this example: stackblitz example
来源:https://stackoverflow.com/questions/29241442/decimal-to-rgb-in-javascript-and-php