Color Conversion - gchudnov/cpp-colors GitHub Wiki

When printed to a stream, the color value is always represented as argb(AA,RR,GG,BB) no matter what the internal pixel format is:

  // typedef basic_color<uint8_t, rgba32_traits> color_abrg; // defined in the library

  color c1(255, 128, 64, 32);
  color_abrg c2(c1);

  cout << "c1: " << c1 << endl; // argb(255,128,64,32)
  cout << "c2: " << c2 << endl; // argb(255,128,64,32)

When printed as a value, the color represented as a 32-bit ARGB value with alpha (8 bits per channel) by default:

  color c1(255, 128, 64, 32);
  cout << "c1 value: " << hex << c1.value() << endl; // ff804020

To print the value in a different pixel format, (1) define a different color type:

  // typedef basic_color<uint8_t, rgba32_traits> color_abrg; // defined in the library
  color_abrg c2(255, 128, 64, 32);
  cout << "c2 value: " << hex << c2.value() << endl; // ff204080

OR

(2) Convert a color-value to a different binary representation using the value member function:

  uint32_t val = c.value<pixel_format::FORMAT>(); 

FORMAT: a value from pixel_format enum. The following pixel formats are supported out-of-the box:

      bgr24,              // 24-bit RGB pixel format with 8 bits per channel.                                              r8g8b8
      color, /* bgra32 */ // 32-bit ARGB pixel format with alpha, using 8 bits per channel.                                a8r8g8b8
      bgr32,              // 32-bit RGB pixel format, where 8 bits are reserved for each color.                            x8r8g8b8
      bgr565,             // 16-bit RGB pixel format with 5 bits for red, 6 bits for green, and 5 bits for blue.           r5g6b5
      bgr555,             // 16-bit pixel format where 5 bits are reserved for each color.                                 x1r5g5b5
      bgra5551,           // 16-bit pixel format where 5 bits are reserved for each color and 1 bit is reserved for alpha. a1r5g5b5
      rgba32,             // 32-bit ABGR pixel format with alpha, using 8 bits per channel.                                a8b8g8r8
      rgb32,              // 32-bit BGR pixel format, where 8 bits are reserved for each color.                            x8b8g8r8

For example:

  // ARGB32
  color c1(255, 128, 64, 32);

  // BGR24 (no alpha): 00804020
  cout << "BGR24 (no alpha): "<< hex << setfill('0') << setw(8) << c1.value<pixel_format::bgr24>() << endl;

  // BGR565 (no alpha): 8204
  cout << "BGR565 (no alpha): "<< hex << setfill('0') << setw(4) << c1.value<pixel_format::bgr565>() << endl;