CFileDialog dlg(false,"*.bmp",NULL,NULL,"*.bmp|*.bmp||");
if (dlg.DoModal()==IDOK) { SaveBitmapToFile(hBitmap,dlg.GetPathName()); PostQuitMessage(0); } //------------保存Bitmap到文件--------------- BOOL SaveBitmapToFile(HBITMAP hBitmap, LPCTSTR lpFileName ) { HDC hDC; //設(shè)備描述表 int iBits; //當(dāng)前顯示分辨率下每個(gè)像素所占字節(jié)數(shù) WORD wBitCount; //位圖中每個(gè)像素所占字節(jié)數(shù) DWORD dwPaletteSize=0, //定義調(diào)色板大小, 位圖中像素字節(jié)大小 ,,位圖文件大小 ,, 寫入文件字節(jié)數(shù) dwBmBitsSize, dwDIBSize, dwWritten; BITMAP Bitmap; //位圖屬性結(jié)構(gòu) BITMAPFILEHEADER bmfHdr; //位圖文件頭結(jié)構(gòu) BITMAPINFOHEADER bi; //位圖信息頭結(jié)構(gòu) LPBITMAPINFOHEADER lpbi; //指向位圖信息頭結(jié)構(gòu) HANDLE fh, hDib, hPal,hOldPal=NULL; //定義文件,分配內(nèi)存句柄,,調(diào)色板句柄 //計(jì)算位圖文件每個(gè)像素所占字節(jié)數(shù) HDC hWndDC = CreateDC("DISPLAY",NULL,NULL,NULL); hDC = ::CreateCompatibleDC( hWndDC ) ; iBits = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES); DeleteDC(hDC); if (iBits <= 1) wBitCount = 1; else if (iBits <= 4) wBitCount = 4; else if (iBits <= 8) wBitCount = 8; else if (iBits <= 24) wBitCount = 24; else wBitCount = 24 ; //計(jì)算調(diào)色板大小 if (wBitCount <= 8) dwPaletteSize = (1 << wBitCount) * sizeof(RGBQUAD); //設(shè)置位圖信息頭結(jié)構(gòu) GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&Bitmap); bi.biSize = sizeof(BITMAPINFOHEADER); bi.biWidth = Bitmap.bmWidth; bi.biHeight = Bitmap.bmHeight; bi.biPlanes = 1; bi.biBitCount = wBitCount; bi.biCompression = BI_RGB; bi.biSizeImage = 0; bi.biXPelsPerMeter = 0; bi.biYPelsPerMeter = 0; bi.biClrUsed = 0; bi.biClrImp dwBmBitsSize = ((Bitmap.bmWidth * wBitCount+31)/32) * 4 * Bitmap.bmHeight ; //為位圖內(nèi)容分配內(nèi)存 hDib = GlobalAlloc(GHND,dwBmBitsSize+dwPaletteSize+sizeof(BITMAPINFOHEADER)); lpbi = (LPBITMAPINFOHEADER)GlobalLock(hDib); *lpbi = bi; // 處理調(diào)色板 hPal = GetStockObject(DEFAULT_PALETTE); if (hPal) { hDC = ::GetDC(NULL); hOldPal = ::SelectPalette(hDC, (HPALETTE)hPal, FALSE); RealizePalette(hDC); } // 獲取該調(diào)色板下新的像素值 GetDIBits(hDC, hBitmap, 0, (UINT) Bitmap.bmHeight, (LPSTR)lpbi + sizeof(BITMAPINFOHEADER) +dwPaletteSize, (LPBITMAPINFO ) lpbi, DIB_RGB_COLORS); //恢復(fù)調(diào)色板 if (hOldPal) { SelectPalette(hDC, (HPALETTE)hOldPal, TRUE); RealizePalette(hDC); ::ReleaseDC(NULL, hDC); } //創(chuàng)建位圖文件 fh = CreateFile(lpFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (fh == INVALID_HANDLE_VALUE) return FALSE; // 設(shè)置位圖文件頭 bmfHdr.bfType = 0x4D42; // "BM" dwDIBSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + dwPaletteSize + dwBmBitsSize; bmfHdr.bfSize = dwDIBSize; bmfHdr.bfReserved1 = 0; bmfHdr.bfReserved2 = 0; bmfHdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER) + dwPaletteSize; // 寫入位圖文件頭 WriteFile(fh, (LPSTR)&bmfHdr, sizeof(BITMAPFILEHEADER), &dwWritten, NULL); // 寫入位圖文件其余內(nèi)容 WriteFile(fh, (LPSTR)lpbi, dwDIBSize, &dwWritten, NULL); //清除 GlobalUnlock(hDib); GlobalFree(hDib); CloseHandle(fh); return TRUE; } |
|