I have some colors that seem to come from a Delphi TColor variable (e.g 8388608, 128, 12632256). I need to convert those colors to their rgb values with a PHP script. How can this be done in PHP?
+8
A:
The Delphi TColor
type is an integer whose bits contain the actual RGB values like this:
ssBBGGRR
Extracting RGB values:
You can filter out the parts by doing a bit-wise AND
with 0xFF
, while shifting the bits to the right.
Delphi code:
R := Color and $FF;
G := (Color shr 8) and $FF;
B := (Color shr 16) and $FF;
PHP code:
R = Color & 0xFF;
G = (Color >> 8) & 0xFF;
B = (Color >> 16) & 0xFF;
Warning about system colors:
There are special colors which are derived from the system colors. (like button and window colors)
Those colors don't actually have valid RGB values set. You can detect them by checking the first eight bits. If they are non-zero you have a special system color. You can also cast the color to an integer. If it is negative, it's a system color.
In that case the R part contains the system color index.
DR
2009-07-14 13:24:27
I thought that TColor was, bizarrely, BGR;- (from the help file) If you specify TColor as a specific 4-byte hexadecimal number instead of using the constants defined in the Graphics unit, the low three bytes represent RGB color intensities for blue, green, and red, respectively. The value $00FF0000 (Delphi) or 0x00FF0000 (C++) represents full-intensity, pure blue, $0000FF00 (Delphi) or 0x0000FF00 (C++) is pure green, and $000000FF (Delphi) or 0x000000FF (C++) is pure red. $00000000 (Delphi) or 0x00000000 (C++) is black and $00FFFFFF (Delphi) or 0x00FFFFFF (C++) is white.
robsoft
2009-07-14 13:31:15
Actually, TColor in Delphi is TTBBGGRR (T = transparency, or alpha channel, whatever you want to call it), not RRGGBB. HTML color is TTRRGGBB. So you have to exchange RR and BB parts. Someone fluent in PHP will show how, I have no idea ...
gabr
2009-07-14 13:31:38
It's not bizarr, it's just "little endian" where the "small bits" are at the end of the number :)
DR
2009-07-14 13:33:51
@gabr: That's not true, the first 8 bits are used to mark the color as system color. There's no alpha channel in TColor.
DR
2009-07-14 13:38:08
Ah, got that part wrong. Thanks for the correction. Still, it is ssBBGGRR, not ssRRGGBB as your answer says.
gabr
2009-07-14 13:39:48
OK, thank you, too :)
DR
2009-07-14 13:40:22
Excellent answer (now :) ) +1
gabr
2009-07-14 13:57:38
Are you saying that little-endian is *not* a bizarre way to represent numbers, DR? ;)
Mason Wheeler
2009-07-14 14:46:43
Tcolor is that TTBBGGRR on little-endian. We'll have to wait to see what it will be on big-endian machines :)
Marco van de Voort
2009-07-14 16:19:56
Well, little-endian ssBBGGRR is RRGGBBss in memory.
Barry Kelly
2009-07-14 17:00:46