Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split ARGB into byte values

I have a ARGB value stored as an int type. It was stored by calling ToArgb.

I now want the byte values of the individual color channels from the int value.

for example

int mycolor = -16744448;
byte r,g,b,a;

GetBytesFromColor(mycolor,out a, out r, out g, out b);

How would you implement GetBytesFromColor?

To give the context I am passing a color value persisted in db as int to a silverlight application which needs the individual byte values to construct a color object.

System.Windows.Media.Color.FromArgb(byte a, byte r, byte g, byte b)
like image 258
Pradeep Avatar asked Aug 25 '09 13:08

Pradeep


2 Answers

public void GetBytesFromColor(int color, out a, out r, out g, out b)
{
    Color c = Color.FromArgb(color);
    a = c.A;
    r = c.R;
    g = c.G;
    b = c.B;
}
like image 133
ba__friend Avatar answered Nov 01 '22 13:11

ba__friend


You are after the 4 successive 8-bit chunks from a 32-bit integer; so a combination of masking and shifting:

b = (byte)(myColor & 0xFF);
g = (byte)((myColor >> 8) & 0xFF);
r = (byte)((myColor >> 16) & 0xFF);
a = (byte)((myColor >> 24) & 0xFF);
like image 14
Marc Gravell Avatar answered Nov 01 '22 14:11

Marc Gravell