Bool savebmp (HDC, const tstring & filepath) {hbitmap HBM = (hbitmap) getcurrentobject (HDC, obj_bitmap); Assert (HBM); Return savebmp (HBM, filepath );} bool savebmp (hbitmap HBM, const tstring & filepath) {lpbyte pbitmap = NULL; bool balloc = false; bitmap Bm = {0}; Assert (GetObject (HBM, sizeof (Bitmap ), & BM); Assert (BM. bmwidth & amp; BM. bmheight); If (! BM. bmbits) {long size = BM. bmwidthbytes * BM. bmheight; pbitmap = new byte [size]; balloc = true; Assert (getbitmapbits (HBM, size, pbitmap) = size);} else {pbitmap = (lpbyte) BM. bmbits;} bitmapfileheader BFH = {0}; BFH. bftype = 0x4d42; BFH. bfsize = BM. bmwidthbytes * BM. bmheight + sizeof (bitmapfileheader) + sizeof (bitmapinfoheader); BFH. bfoffbits = sizeof (bitmapfileheader) + sizeof (bitmapinfoheader); bitmapinfo BMI = {0}; BMI. bmiheader. bisize = sizeof (bitmapinfoheader); BMI. bmiheader. biwidth = BM. bmwidth; BMI. bmiheader. biheight =-BM. bmheight; BMI. bmiheader. biplanes = BM. bmplanes; BMI. bmiheader. bibitcount = BM. bmbitspixel; BMI. bmiheader. bicompression = bi_rgb; BMI. bmiheader. bisizeimage = BM. bmwidthbytes * BM. bmheight; BMI. bmiheader. bixpelspermeter = 0; BMI. bmiheader. biypelspermeter = 0; BMI. bmiheader. biclrused = 0; BMI. bmiheader. biclrimportant = 0; file * fp = NULL; _ tfopen_s (& FP, filepath. c_str (), _ T ("WB"); Assert (FP); size_t writecount = fwrite (& BFH, sizeof (bitmapfileheader), 1, FP ); assert (writecount = 1); writecount = fwrite (& BMI, sizeof (bitmapinfoheader), 1, FP); Assert (writecount = 1); writecount = fwrite (pbitmap, BMI. bmiheader. bisizeimage, 1, FP); Assert (writecount = 1); fclose (FP); If (balloc & pbitmap) Delete [] pbitmap; return true ;}
Note:
1) do not use SelectObject to obtain the bitmap of HDC. This is more complicated, and SelectObject can only obtain the bitmap of memory DC.
2) When GetObject is used, the content pointer bibits In the bitmap struct is non-zero only when hbitmap is the handle returned by createdibsection, otherwise, you need to use the getbitmapbits function again to obtain the corresponding bitmap buffer.