在C++中要将一张位图信息BITMAPINFOHEADER读取并显示在一个控件上,具体步骤如下:
1.先读取位图信息
int ReadPictureBmp(unsigned char *pBmpBuffer)
{
// static int i=0;
// if (i>5)
// {
// return TRUE;
// }
FILE *fp = NULL;
char szFileName[MAX_PATH] = {0};
sprintf(szFileName, "E:\\工作目录\\20141008_162621_28826078.bmp");
fp = fopen( szFileName, "rb");
if( fp == NULL )
{
return FALSE;
}
long lSize;
/* 获取文件大小 */
fseek (fp , 0 , SEEK_END);
lSize = ftell (fp);
rewind (fp);
// pBmpBuffer = new unsigned char[lSize];
long res = fread(pBmpBuffer,1,lSize,fp);
if ( res != lSize )
{
printf_s( "res \n" );
}
fclose(fp);
fp = NULL;
return TRUE;
}
2.为显示位图做准备
bool PrepareDibBuffer(LPBITMAPINFO *lplpbi, DWORD dwX, DWORD dwY)
{
HDC hdc;
LPBITMAPINFOHEADERlpbih;
//Allocate buffer
*lplpbi = new BITMAPINFO;
lpbih = (LPBITMAPINFOHEADER)*lplpbi;
hdc = ::GetDC(NULL);
//Fill information BITMAPINFOHEADER
lpbih->biSize = sizeof(BITMAPINFOHEADER);
lpbih->biWidth = dwX;
lpbih->biHeight = dwY;
lpbih->biPlanes = 1;
lpbih->biBitCount = 24;
lpbih->biCompression = BI_RGB;
lpbih->biSizeImage = 0;
lpbih->biXPelsPerMeter = (GetDeviceCaps(hdc, HORZRES) * 1000) / GetDeviceCaps(hdc, HORZSIZE);
lpbih->biYPelsPerMeter = (GetDeviceCaps(hdc, VERTRES) * 1000) / GetDeviceCaps(hdc, VERTSIZE);
lpbih->biClrUsed = 0;
lpbih->biClrImportant = 0;
lpbih->biSizeImage = 0;
::ReleaseDC(NULL, hdc);
return TRUE;
}
3.调用函数显示位图
void ShowBmp(HWND hwnd)
{
unsigned char *pPicBmpbuf;
pPicBmpbuf = new unsigned char[1024*1024*2];
RECT rect;
::GetWindowRect(hwnd, &rect);
DWORD dwWidth = rect.right - rect.left;
DWORD dwHeight = rect.bottom - rect.top;
ReadPictureBmp(pPicBmpbuf);
HDC hDrawDC;
hDrawDC = ::GetDC(hwnd);
::SetStretchBltMode(hDrawDC, COLORONCOLOR);//删除设备中像素行
BITMAPINFO* pBmi;
PrepareDibBuffer(&pBmi, nImgwidth, nImgHeight);
//左上角 StretchDIBits此函数允许 JPEG 或 PNG 图像作为源图像传入,此处一定要去掉位图信息的头sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER),不然
//显示位图会有问题
::StretchDIBits(hDrawDC, 0, 0, dwWidth, dwHeight, \
0 ,0, pBmi->bmiHeader.biWidth, pBmi->bmiHeader.biHeight, \
(const void*)(pPicBmpbuf+sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)), \
pBmi, DIB_RGB_COLORS, SRCCOPY);
::ReleaseDC(hwnd, hDrawDC);
if (pPicBmpbuf)
{
delete []pPicBmpbuf;
pPicBmpbuf = NULL;
}
if(pBmi)
{
delete []pBmi;
pBmi=NULL;
}
}