您的位置:首页 > 其它

[SDK]创建DC,保存DC为BMP文件

2015-04-07 13:18 169 查看
HDC CreateBitmapDC(LONG Width, LONG Height)
{
HDC hDC, hMemDC;
BITMAPINFO bi;
HBITMAP hBitmap;
PVOID Bits;

hDC = NULL;
hMemDC = CreateCompatibleDC(NULL);
memset(&bi, 0, sizeof(bi));
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bi.bmiHeader.biWidth = Width;
bi.bmiHeader.biHeight = Height;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = 24;
if (hBitmap = CreateDIBSection(hMemDC, &bi, DIB_RGB_COLORS, &Bits, NULL, 0))
{
DeleteObject(SelectObject(hMemDC, hBitmap));
hDC = hMemDC;
}
else
{
DeleteDC(hMemDC);
}
return hDC;// use DeleteDC to free handle
}

BOOL SaveDCToFile(HDC hDc, TCHAR *lpFile)
{
BOOL bRet;

bRet = FALSE;
if (HBITMAP hBitmap = (HBITMAP)GetCurrentObject(hDc, OBJ_BITMAP))
{
BITMAP bm;

if (GetObject(hBitmap, sizeof(bm), &bm) != 0)
{
BITMAPFILEHEADER bfh;
BITMAPINFOHEADER bih;
HANDLE hFile;

memset(&bfh, 0, sizeof(bfh));
memset(&bih, 0, sizeof(bih));
bfh.bfType = 0x4D42; // "BM"
bfh.bfSize = 0;
bfh.bfOffBits = sizeof(bfh) + sizeof(bih);

bih.biSize = sizeof(bih);
bih.biWidth = bm.bmWidth;
bih.biHeight = bm.bmHeight;
bih.biPlanes = bm.bmPlanes;
bih.biBitCount = bm.bmBitsPixel;
bih.biCompression = BI_RGB;

hFile = CreateFile(lpFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
DWORD dwOpt;

if (WriteFile(hFile, &bfh, sizeof(bfh), &dwOpt, NULL)
&& WriteFile(hFile, &bih, sizeof(bih), &dwOpt, NULL)
&& WriteFile(hFile, bm.bmBits, bm.bmWidthBytes * bm.bmHeight, &dwOpt, NULL))
{
bRet = TRUE;
}
CloseHandle(hFile);
}
}
}
return bRet;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: