teObject((HGDIOBJ)hfont);
DeleteObject((HGDIOBJ)hbm);
DeleteDC(memDC);
return 0;
}
3 将HBITMAP保存为BMP图片
第2节描述了如何使用GDI在内存中画图,本节介绍如何将HBITMAP保存为BMP图片。代码如下:
[cpp]
/**
* 将HBITMAP保存为BMP图片
*/
void hbitmapToImage(HDC hdc, HBITMAP hbm)
{
// 得到hbm中每个像素所占的位数
int bmPixBitCount = GetDeviceCaps(hdc, BITSPIXEL) * GetDeviceCaps(hdc, PLANES);
int wBitCount = 0;
if(bmPixBitCount <= 1)
wBitCount = 1;
else if(bmPixBitCount <= 4)
wBitCount = 4;
else if(bmPixBitCount <= 8)
wBitCount = 8;
else
wBitCount = 24;
//////////////////////////////////////////////////////////////////////////
BITMAP bm;
GetObject(hbm, sizeof(bm), &bm);
int bmRowCount = ((bm.bmWidth * wBitCount + 31) / 32) * 4; // 一行所占的字节数,BMP像素数据按四字节对齐
int bmByteCount = bmRowCount * bm.bmHeight; // 像素数据的大小
char *buf = new char[bmByteCount];
// 位图信息头结构,定义参考MSDN
BITMAPINFOHEADER bi;
bi.biSize= sizeof(BITMAPINFOHEADER);
bi.biWidth = bm.bmWidth;
bi.biHeight = bm.bmHeight;
bi.biPlanes = 1;
bi.biBitCount = wBitCount;
bi.biCompression= BI_RGB;
bi.biSizeImage=0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrImportant = 0;
bi.biClrUsed = 0;
GetDIBits(hdc, hbm, 0, bm.bmHeight, buf, (BITMAPINFO*)(&bi), DIB_RGB_COLORS); // 得到像素值,保存在buf中
// 位图文件头结构,定义参考MSDN
BITMAPFILEHEADER bf;
bf.bfType = 0x4D42; // BM
bf.bfSize = bmByteCount;
bf.bfReserved1 = 0;
bf.bfReserved2 = 0;
bf.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
// 写入文件
FILE *bmFile = fopen("demo.bmp", "w+b");
if (bmFile)
{
fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, bmFile); // 写入位图文件头
fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, bmFile); // 写入位图信息头
fwrite(buf, sizeof(char), bmByteCount, bmFile); // 写入像素数据
fclose(bmFile);
}
delete []buf;
}
/**
* 将HBITMAP保存为BMP图片
*/
void hbitmapToImage(HDC hdc, HBITMAP hbm)
{
// 得到hbm中每个像素所占的位数
int bmPixBitCount = GetDeviceCaps(hdc, BITSPIXEL) * GetDeviceCaps(hdc, PLANES);
int wBitCount = 0;
if(bmPixBitCount <= 1)
wBitCount = 1;
else if(bmPixBitCount <= 4)
wBitCount = 4;
else if(bmPixBitCount <= 8)
wBitCount = 8;
else
wBitCount = 24;
//////////////////////////////////////////////////////////////////////////
BITMAP bm;
GetObject(hbm, sizeof(bm), &bm);
int bmRowCount = ((bm.bmWidth * wBitCount + 31) / 32) * 4; // 一行所占的字节数,BMP像素数据按四字节对齐
int bmByteCount = bmRowCount * bm.bmHeight; // 像素数据的大小
char *buf = new char[bmByteCount];
// 位图信息头结构,定义参考MSDN
BITMAPINFOHEADER bi;
bi.biSize= sizeof(BITMAPINFOHEADER);
bi.biWidth = bm.bmWidth;
bi.biHeight = bm.bmHeight;
bi.biPlanes = 1;
bi.biBitCount = wBitCount;
bi.biCompression= BI_RGB;
bi.biSizeImage=0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrImportant = 0;
bi.biCl