如何使用 LoadImage() 讀取 BMP 檔案

LoadImage API 可以用來從 BMP 檔案載入點陣圖。 不過,它不會傳回調色盤的資訊。 本文提供範例程式碼,並說明如何擷取 LoadImage 的點陣圖的調色盤資訊。
下列程式碼會使用 LoadImage API,以載入點陣圖為一的 DIBSection,,然後從 DIBSection 的色彩表中建立調色盤。 如果沒有色彩表存在,會使用半色調調色盤:
BOOL LoadBitmapFromBMPFile( LPTSTR szFileName, HBITMAP *phBitmap,
   HPALETTE *phPalette )
   {

   BITMAP  bm;

   *phBitmap = NULL;
   *phPalette = NULL;

   // Use LoadImage() to get the image loaded into a DIBSection
   *phBitmap = (HBITMAP)LoadImage( NULL, szFileName, IMAGE_BITMAP, 0, 0,
               LR_CREATEDIBSECTION | LR_DEFAULTSIZE | LR_LOADFROMFILE );
   if( *phBitmap == NULL )
     return FALSE;

   // Get the color depth of the DIBSection
   GetObject(*phBitmap, sizeof(BITMAP), &bm );
   // If the DIBSection is 256 color or less, it has a color table
   if( ( bm.bmBitsPixel * bm.bmPlanes ) <= 8 )
   {
   HDC           hMemDC;
   HBITMAP       hOldBitmap;
   RGBQUAD       rgb[256];
   LPLOGPALETTE  pLogPal;
   WORD          i;

   // Create a memory DC and select the DIBSection into it
   hMemDC = CreateCompatibleDC( NULL );
   hOldBitmap = (HBITMAP)SelectObject( hMemDC, *phBitmap );
   // Get the DIBSection's color table
   GetDIBColorTable( hMemDC, 0, 256, rgb );
   // Create a palette from the color tabl
   pLogPal = (LOGPALETTE *)malloc( sizeof(LOGPALETTE) + (256*sizeof(PALETTEENTRY)) );
   pLogPal->palVersion = 0x300;
   pLogPal->palNumEntries = 256;
   for(i=0;i<256;i++)
   {
     pLogPal->palPalEntry[i].peRed = rgb[i].rgbRed;
     pLogPal->palPalEntry[i].peGreen = rgb[i].rgbGreen;
     pLogPal->palPalEntry[i].peBlue = rgb[i].rgbBlue;
     pLogPal->palPalEntry[i].peFlags = 0;
   }
   *phPalette = CreatePalette( pLogPal );
   // Clean up
   free( pLogPal );
   SelectObject( hMemDC, hOldBitmap );
   DeleteDC( hMemDC );
   }
   else   // It has no color table, so use a halftone palette
   {
   HDC    hRefDC;

   hRefDC = GetDC( NULL );
   *phPalette = CreateHalftonePalette( hRefDC );
   ReleaseDC( NULL, hRefDC );
   }
   return TRUE;

   }
下列程式碼會示範如何使用 LoadBitmapFromBMPFile 函式:
 case WM_PAINT:
   {
     PAINTSTRUCT   ps;
     HBITMAP       hBitmap, hOldBitmap;
     HPALETTE      hPalette, hOldPalette;
     HDC           hDC, hMemDC;
     BITMAP        bm;

   hDC = BeginPaint( hWnd, &ps );

   if( LoadBitmapFromBMPFile( szFileName, &hBitmap, &hPalette ) )
   {
      GetObject( hBitmap, sizeof(BITMAP), &bm );
      hMemDC = CreateCompatibleDC( hDC );
      hOldBitmap = (HBITMAP)SelectObject( hMemDC, hBitmap );
      hOldPalette = SelectPalette( hDC, hPalette, FALSE );
      RealizePalette( hDC );

      BitBlt( hDC, 0, 0, bm.bmWidth, bm.bmHeight,
              hMemDC, 0, 0, SRCCOPY );

      SelectObject( hMemDC, hOldBitmap );
      DeleteObject( hBitmap );
      SelectPalette( hDC, hOldPalette, FALSE );
      DeleteObject( hPalette );
   }
   EndPaint( hWnd, &amp;ps );

   }
   break;


posted @ 2008-12-11 16:39  荷包蛋  阅读(2960)  评论(0编辑  收藏  举报