简体   繁体   中英

How can I convert a hexadecimal number to RGB in PHP

I am trying to convert a hexadecimal value such as 0x4999CB (for use as an RGB color) into its color "components" to use in functions eg imagecolorallocate. How can I extract the RGB values out of the hex value?

I knew that the RGB color values are 8 bits each, or one byte, which is conveniently two digits in hexadecimal. Since there are 256 values for a byte (0-255) I figured there had to be a way to neatly "mathify" the values out of the hexadecimal representation.

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

You can "function-ify" this:

function hex2rgb($hex = 0x0) {
    $rgb = array();
    $rgb['r'] = floor($hex / 65536);
    $rgb['g'] = floor($hex / 256) % 256;
    $rgb['b'] = $hex % 256;
    return $rgb;
}

Or if you're one of those perverse people who loves compact code even at the expense of readability:

function hex2rgb($h = 0) {
    return array('r'=>floor($h/65536),'g'=>floor($h/256)%256,'b'=>$h%256);
}

(and if you're okay with numeric indices you can even go smaller:)

function hex2rgb($h = 0) {
    return array(floor($h/65536),floor($h/256)%256,$h%256);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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