Javascript和PHP中的十进制到RGB [英] Decimal to RGB in Javascript and PHP

查看:104
本文介绍了Javascript和PHP中的十进制到RGB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将十进制值转换回RGB值。

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

(例如rgb(16,120,78)加起来为1071078)

(For example rgb(16,120,78) adds up to 1071078)

如何解决r,g和b没有任何溢出?

How would one solve r, g and b without any "overflow"?

提前致谢!

推荐答案

使用除法,模数()和最低四舍五入:

Use division, modulo (%) and floor rounding:

var r = Math.floor(c / (256*256));
var g = Math.floor(c / 256) % 256;
var b = c % 256;



编辑:



halex发现差异在代码中使用255和256。当你把组件放在一起时,你应该(如Millie Smith指出的那样)使用256而不是255:

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;

颜色组件的值可以是0到255,所以你需要乘以256来保持下一个组件与前一个重叠。

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.

这篇关于Javascript和PHP中的十进制到RGB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆