繁体   English   中英

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

[英]How can I convert a hexadecimal number to RGB in PHP

我正在尝试将十六进制值(例如0x4999CB (用作RGB颜色))转换为其颜色“分量”,以用于诸如imagecolorallocate的函数中。 如何从十六进制值中提取RGB值?

我知道RGB颜色值分别是8位或1个字节,即十六进制的两位数。 由于一个字节(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($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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM