Voting

: eight minus two?
(Example: nine)

The Note You're Voting On

Richard
16 years ago
With the following functions you can not only convert a 24 bit RGB integer to its corresponding red, green, and blue values, but also 32 bit RGBA integers to its corresponding red, green, blue, and ALPHA values.

Not only that, but I even threw in a function for converting those red, green, blue, and alpha values back into a 32 bit RGBA integer.

Sample usage:
<?php
$int
= rgba2int(255, 255, 255, 16);
echo
$int . "<br>";
$rgba = int2rgba($int);
print_r($rgba);
?>

What it should output:
285212671
Array
(
[r] => 255
[g] => 255
[b] => 255
[a] => 16
)

<?php
function rgba2int($r, $g, $b, $a=1) {
/*
This function builds a 32 bit integer from 4 values which must be 0-255 (8 bits)
Example 32 bit integer: 00100000010001000000100000010000
The first 8 bits define the alpha
The next 8 bits define the blue
The next 8 bits define the green
The next 8 bits define the red
*/
return ($a << 24) + ($b << 16) + ($g << 8) + $r;
}

function
int2rgba($int) {
$a = ($int >> 24) & 0xFF;
$r = ($int >> 16) & 0xFF;
$g = ($int >> 8) & 0xFF;
$b = $int & 0xFF;
return array(
'r'=>$r, 'g'=>$g, 'b'=>$b, 'a'=>$a);
}
?>

<< Back to user notes page

To Top