vc读写BMP文件代码
作者:cnfgg 日期:2009-06-29
读取BMP的代码:
复制内容到剪贴板
程序代码
程序代码void LoadDIBFile(LPSTR lpFilePath,unsigned char *pDIB)
{
BITMAPFILEHEADER bmfHeader;
BITMAPINFOHEADER bmfInfo;
//open the dib file
HANDLE hFile = CreateFile(lpFilePath,GENERIC_READ,NULL,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwSizeRead;
if(!ReadFile(hFile,(LPBITMAPFILEHEADER)&bmfHeader,sizeof(bmfHeader),&dwSizeRead,NULL))
{
::CloseHandle(hFile);
return;
}
if(!ReadFile(hFile,(LPBITMAPFILEHEADER)&bmfInfo,sizeof(bmfInfo),&dwSizeRead,NULL))
{
::CloseHandle(hFile);
return;
}
int nSize = GetFileSize(hFile,NULL) - sizeof(BITMAPFILEHEADER) - sizeof(BITMAPINFOHEADER);
//check the file is DIB
DWORD dwFileType = ((DWORD)('M'<<8)|'B');
if(bmfHeader.bfType != dwFileType)
{
::CloseHandle(hFile);
return;
}
// Read all lines (from bottom up)
int LineSize=bmfInfo.biWidth*bmfInfo.biBitCount/8;
int Offs=LineSize*(bmfInfo.biHeight-1);
for(int i=0;i<(UINT32)bmfInfo.biHeight;i++)
{
ReadFile(hFile,pDIB+Offs,LineSize,&dwSizeRead,NULL);
Offs-=LineSize;
}
::CloseHandle(hFile);
}
存储BMP的代码:
复制内容到剪贴板
程序代码
程序代码BOOL WriteBitmap(char *pFilename, UINT8 *pImage, BITMAPINFO *pInfo)
{
OFSTRUCT Ofs;
HFILE hFile;
DWORD i,LineSize,Offs;
BITMAPFILEHEADER fh;
BITMAPINFOHEADER bmi;
if(!pInfo||!pImage)
return FALSE;
hFile=OpenFile(pFilename,&Ofs,OF_Create);
if(hFile==HFILE_ERROR)
return FALSE;
// Copy Bitmapinfoheader (set Width and Height absolute)
bmi=pInfo->bmiHeader;
bmi.biWidth=abs(pInfo->bmiHeader.biWidth);
bmi.biHeight=abs(pInfo->bmiHeader.biHeight);
#define BMTYPE 0x4d42
// Build fileheader and write
fh.bfType=BMTYPE;
if(pInfo->bmiHeader.biBitCount==8)
{
fh.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+
256*sizeof(RGBQUAD);
fh.bfSize=fh.bfOffBits+pInfo->bmiHeader.biSizeImage;
bmi.biClrUsed=256;
bmi.biClrImportant=0;
}
else
{
fh.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);
fh.bfSize =fh.bfOffBits+pInfo->bmiHeader.biSizeImage;
bmi.biClrUsed=0;
bmi.biClrImportant=0;
}
fh.bfReserved1=0;
fh.bfReserved2=0;
// Write fileheader
_hwrite(hFile,(char*)&fh,sizeof(BITMAPFILEHEADER));
// Write bitmapinfoheader
_hwrite(hFile,(char*)&bmi,sizeof(BITMAPINFOHEADER));
// Write Palette (only if grayscale)
if(bmi.biClrUsed!=0)
_hwrite(hFile,(char*)pInfo->bmiColors,pInfo->bmiHeader.biClrUsed*sizeof(RGBQUAD));
// Write all lines (from bottom up)
LineSize=bmi.biWidth*bmi.biBitCount/8;
Offs=LineSize*(bmi.biHeight-1);
for(i=0;i<(UINT32)bmi.biHeight;i++)
{
_hwrite(hFile,(char*)&pImage[Offs],LineSize);
Offs-=LineSize;
}
_lclose(hFile);
return TRUE;
}
评论: 0 | 引用: 0 | 查看次数: -
发表评论
上一篇
下一篇

文章来自:
Tags:
相关日志: