簡體   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