如何在PHP中将十六进制数转换为RGB

如何在PHP中将十六进制数转换为RGB,php,image,gd,Php,Image,Gd,我正在尝试将一个十六进制值(如0x4999CB(用作RGB颜色)转换为其颜色“组件”,以便在函数(如imagecolorallocate)中使用。如何从十六进制值中提取RGB值?我知道RGB颜色值是每个8位,或者一个字节,也就是两个十六进制数字。因为一个字节(0-255)有256个值,所以我认为必须有一种方法来巧妙地将十六进制表示的值“数学化” $val = 0x4999CB; // starting with blue since that seems the most straightfo

我正在尝试将一个十六进制值(如
0x4999CB
(用作RGB颜色)转换为其颜色“组件”,以便在函数(如imagecolorallocate)中使用。如何从十六进制值中提取RGB值?

我知道RGB颜色值是每个8位,或者一个字节,也就是两个十六进制数字。因为一个字节(0-255)有256个值,所以我认为必须有一种方法来巧妙地将十六进制表示的值“数学化”

$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 hex2rgb($h = 0) {
    return array('r'=>floor($h/65536),'g'=>floor($h/256)%256,'b'=>$h%256);
}
(如果你对数字索引没意见,你甚至可以缩小:)

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);
}