MFC/Bitmap

Writing a window image to a BMP file

곰돌이짱 2013. 8. 8. 17:56
  1. BOOL WriteWindowToDIB( LPTSTR szFile, CWnd *pWnd )
  2. {
  3. CBitmap bitmap;
  4. CWindowDC dc(pWnd);
  5. CDC memDC;
  6. CRect rect;
  7.  
  8. memDC.CreateCompatibleDC(&dc);
  9.  
  10. pWnd->GetWindowRect(rect);
  11.  
  12. bitmap.CreateCompatibleBitmap(&dc, rect.Width(),rect.Height() );
  13. CBitmap* pOldBitmap = memDC.SelectObject(&bitmap);
  14. memDC.BitBlt(0, 0, rect.Width(),rect.Height(), &dc, 0, 0, SRCCOPY);
  15.  
  16. // Create logical palette if device support a palette
  17. CPalette pal;
  18. if( dc.GetDeviceCaps(RASTERCAPS) & RC_PALETTE )
  19. {
  20. UINT nSize = sizeof(LOGPALETTE) + (sizeof(PALETTEENTRY) * 256);
  21. LOGPALETTE *pLP = (LOGPALETTE *) new BYTE[nSize];
  22. pLP->palVersion = 0x300;
  23.  
  24. pLP->palNumEntries =
  25. GetSystemPaletteEntries( dc, 0, 255, pLP->palPalEntry );
  26.  
  27. // Create the palette
  28. pal.CreatePalette( pLP );
  29.  
  30. delete[] pLP;
  31. }
  32.  
  33. memDC.SelectObject(pOldBitmap);
  34.  
  35. // Convert the bitmap to a DIB
  36. HANDLE hDIB = DDBToDIB( bitmap, BI_RGB, &pal );
  37.  
  38. if( hDIB == NULL )
  39. return FALSE;
  40.  
  41. // Write it to file
  42. WriteDIB( szFile, hDIB );
  43.  
  44. // Free the memory allocated by DDBToDIB for the DIB
  45. GlobalFree( hDIB );
  46. return TRUE;
  47. }