Advertisement

quick color question

Started by August 09, 2001 05:10 AM
4 comments, last by filefor 23 years, 6 months ago
i have a function for creating a 16bit 565 color value: unsigned short MAKECOLOR565(int r,int g,int b) { return ( (b%32) + ((g%64)<<6) + ((r%32)<<11) ); } what i can''t understand is how to extract the rgb values out from any 16bit color, so i could for example change the red intensity or something... i think the modulo is confusing me... hope you can help me out...
The modulo should confuse you, because it is wrong.

  unsigned short MAKECOLOR565(int r,int g,int b){return ( (b%32) + ((g%64)<<6) + ((r%32)<<11) );}  


should be

  unsigned short MAKECOLOR565(int r,int g,int b){return ( (b>>3) | ((g>>2)<<6) | ((r>>3)<<11) );}  


To get the rgb values back out, you can use this....

  char GetRedComponent565(short c){  // you dont really need the &0xFF, its just there  // for completeness...  return (char) (c>>11)<<3)&0xFF;}char GetGreenComponent565(short c){  return (char) (c>>5)<<2)&0xFF;}char GetBlueComponent565(short c){  return (char) (c)<<3)&0xFF;}  


HTH
Advertisement
Duh - I forgot to mention the problem with that last solution....

If you use this method, you may well get some visible banding. (depends on your image) This is because you lost some data in the conversion to 16 bit, and converting back to 24 bit doesnt get it back. The only solution to this is to use some sort of dithering algorithm to get intermediate values - its a bit more than a one liner though...
thanks for your answer!

BTW:
the macro was from the book "tricks of the windows programming gurus", i think i''ll throw it right into my garbage can :-)))

Hehe, I thought it might be (Ive seen that macro a million times )

TOTWGPG is a good book, but there are one or two blunders in the code... bear that in mind when copying the source..
yeah, some code even wont compile :-)

but unforunately, i have to bother you again ( i''m confused again):

in your little snippet, youre using shorts and chars, why not unsigned shorts/chars so i have the full color palette from 0 to 65535?

and, what happens if the values go out of range, i.e. assigning 567 to my char? will the compiler clamp these values ( doing an implicit cast or something) ?

and (oh no one more :-) ), i loose some information with your functions ( i added the ''unsigned'' everywhere):


unsigned short color = MAKECOLOR565(255,0,0); //full red

unsigned char red = GetRedComponent(color);
// red == 248 now, lost some accuracy


sorry to bug you with that again....

This topic is closed to new replies.

Advertisement