typedef union
    unsigned Color;
        unsigned char B, G, R, A;

inline RGB Rgb(int R, int G, int B) {RGB Result = {((COLORREF)((BYTE)(R)|((BYTE)(G) << 8)|((BYTE)(B) << 16)))}; return Result;}
inline RGB Rgb(COLORREF Color) {RGB Result = {Color}; return Result;}

The above is my code for an RBG Data structure. I populate it like so:

PRGB Pixels  = new RGB[100];
CreateDIBitmap(DC, &Info.bmiHeader, CBM_INIT, Pixels, &Info, DIB_RGB_COLORS);    //Populates Pixels with colours..

The problem is that if I do: cout<<Pixels[0].Color; It prints the wrong Colours.. but if I docout<<Pixels[0].R; then it prints the correct R, G, and B values. Can anyone tell me why it never prints Colour Correctly?

Is there a way I can automatically populate Color?

Recommended Answers

All 3 Replies

Are you aware that union types can have constructors, destructors, and member functions (but not virtual ones). Maybe that can help you solve your problem, which I don't quite understand.

Ahh I'm aware that I can have constructors and destructors but after a couple hours I figured out my problem (still unsolved though):

RGB M = Rgb(255, 255, 255);
cout<<M.Color<<endl;            //Prints 16777215. This is correct.
cout<<(int)M.R;                   //Prints 255. This is also correct.

//In my bitmap function:

Pixels = new RGB[Info.bmiHeader.biSizeImage];
SetFilePointer(hFile, bFileHeader.bfOffBits, 0, FILE_BEGIN);
ReadFile(hFile, Pixels, Info.bmiHeader.biSizeImage, &Read, 0);
DC = GetDC(0);
Image = CreateDIBitmap(DC, &Info.bmiHeader, CBM_INIT, Pixels, &Info, DIB_RGB_COLORS);       //Read all values into Pixels.

cout<<Pixels[0].Color;         //Prints 42577 which is wrong. It should be: 5350912
cout<<Pixels[0].R<<end;     //This prints correctly.
cout<<Pixels[0].G<<end;     //This prints correctly.
cout<<Pixels[0].B<<end;     //This prints correctly.

//So I used this to swap them and the Pixels[0].Color prints properly:
    BYTE Red = ((Color & 0xff0000) >> 16);
    BYTE Green = ((Color & 0x00ff00) >> 8);
    BYTE Blue = (Color & 0xff);

    return ((Blue << 16) + (Green << 8) + Red);

How can I just swap all the R's & B's in my bitmap function so that RGB.Color will always print in the RGB format instead of BGR?

I think you are getting confused about how memory is stored on your system. It is not necessarily the same way you place your values in the union. For instance, notice that 42577 in hex is 0x00a651 while 5350912 in hex is 0x51a600. Notice the order there? When all three values are the same (255, for instance) you wont notice that difference.

If you make the following assignments: B=0, G=51, R=102, A=153 and print out the value of Color as hex you will see 0x99663300 - the opposite order of the layout of the struct members in your code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.