HOWTO: Determine the RGB Bits-Per-Pixel for the Display

ID: Q195829

The information in this article applies to:

SUMMARY

For image intensive applications, you often need to know how many bits of red, green, and blue are being used in the current video mode. The sample code included in this article demonstrates one way to derive this information using a technique that works on all Windows platforms.

MORE INFORMATION

The following sample code demonstrates how to derive the bit allocation for the display mode by calculating how many unique values are available for red, green, and blue.

Sample Code

   // Returns the position of the highest order bit in a byte.
   BYTE GetWidth(BYTE b)
   {
     int Count = 0;

     while (b) {
       b >>= 1;
       Count++;
     }

     return Count;
   }

   // GetVideoRGBBitsPerPixel() -
   // 
   // Calculates the number of red, green, and blue bits used in
   // the current display mode.
   // 
   // Return values:
   //   If the display is in a palette mode, rather than an RGB
   //   mode, the function returns FALSE and the RGB bits are not
   //   calculated.
   //   If the display is in an RGB mode then the RGB bits are
   //   derived and the function returns TRUE.
   // 
   BOOL GetVideoRGBBitsPerPixel(LPBYTE lpbRed,   // Bits of red.
                                LPBYTE lpbGreen, // Bits of green.
                                LPBYTE lpbBlue)  // Bits of blue.
   {
     HDC      hdc, hdcMem;
     HBITMAP  hbm;
     COLORREF cr, cr2;
     int      i;
     BYTE     r, g, b;

     // Get the display device.
     hdc = GetDC(NULL);

     // If the display is in a palette mode, then bail out of the process.
     if (GetDeviceCaps(hdc,  RASTERCAPS) & RC_PALETTE) {
         ReleaseDC(NULL, hdc);
         return FALSE;
     }

     // Create a minimal memory surface that has the same
     // properties as the display device.
     hdcMem = CreateCompatibleDC(hdc);
     hbm = CreateCompatibleBitmap(hdc, 1, 1);

     // Prepare the surface for drawing.
     SelectObject(hdcMem, hbm);

     // Initialize the RGB counters, and start color.
     r = g = b = 0;
     cr2 = 0;

     // Loop through shades of gray, and see how many unique
     // red, green, and blue values are represented.
     for (i=1; i<256; i++) {
       cr = SetPixel(hdc, 0, 0, RGB(i, i, i));

       if (GetRValue(cr) != GetRValue(cr2)) r++;
       if (GetGValue(cr) != GetGValue(cr2)) g++;
       if (GetBValue(cr) != GetBValue(cr2)) b++;

       cr2 = cr;
     }

     // Clean up the objects you created.
     DeleteDC(hdcMem);
     DeleteObject(hbm);
     ReleaseDC(NULL, hdc);

     // Get the number of bits needed to represent the
     // number of unique RGB values, and return them.
     *lpbRed   = GetWidth(r);
     *lpbGreen = GetWidth(g);
     *lpbBlue  = GetWidth(b);

     return TRUE;
   }

Additional query words:
Keywords          : kbGDI kbPalettes 
Issue type        : kbhowto

Last Reviewed: November 17, 1998