我正在尝试将十六进制值(例如0x4999CB
(用作RGB颜色))转换为其颜色"组件"用于例如imagecolorallocate。如何从十六进制值中提取RGB值?
答案 0 :(得分:0)
我知道RGB颜色值是每个8位,或者是一个字节,方便地是十六进制的两位数。由于一个字节(0-255)有256个值,我认为必须有一种方法可以整齐地“数学化”#34;十六进制表示中的值。
$val = 0x4999CB;
// starting with blue since that seems the most straightforward
// modulus will give us the remainder from dividing by 256
$blue = $val % 256; // 203, which is 0xCB -- got it!
// red is probably the next easiest...
// dividing by 65536 (256 * 256) strips off the green/blue bytes
// make sure to use floor() to shake off the remainder
$red = floor($val / 65535); // 73, which is 0x49 -- got it!
// finally, green does a little of both...
// divide by 256 to "knock off" the blue byte, then modulus to remove the red byte
$green = floor($val / 256) % 256; // 153, which is 0x99 -- got it!
// Then you can do fun things like
$color = imagecolorallocate($im, $red, $green, $blue);
你可以" function-ify"这样:
function hex2rgb($hex = 0x0) {
$rgb = array();
$rgb['r'] = floor($hex / 65536);
$rgb['g'] = floor($hex / 256) % 256;
$rgb['b'] = $hex % 256;
return $rgb;
}
或者如果你是那些喜欢紧凑代码而又牺牲可读性的乖张的人之一:
function hex2rgb($h = 0) {
return array('r'=>floor($h/65536),'g'=>floor($h/256)%256,'b'=>$h%256);
}
(如果你对数字索引没问题,你甚至可以变小:)
function hex2rgb($h = 0) {
return array(floor($h/65536),floor($h/256)%256,$h%256);
}