I want to convert back and forth between RGBA-formated HEX colors (like0xFF0000FF
) and RGB-formated HEX colors (like 0xFF0000
) in PHP.
How can I do this?
I want to convert back and forth between RGBA-formated HEX colors (like0xFF0000FF
) and RGB-formated HEX colors (like 0xFF0000
) in PHP.
How can I do this?
These two functions will do what you need:
The first one simply removes the last two characters, whilst the second one simply appends
FF
.As Frank mentioned, you can simply strip the last 2 digits.
The hex format is 3 pairs of numbers, the first pair Red value, the next is Green, and the next is blue. If you add another pair, it's assumed to be the alpha value.
How about these:
$blend in the first is effectively a background color to blend with.
Edit: fix due to not enough space in ints ruining RGBA. RGBA is now handled as a four part array. RGB remains a number.:
RGBA -> RGB should be simple, as it's just cutting off the last two digits. The other direction is impossible, as alpha information isn't encoded in RGB.